Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg

PHP : Function Reference : Regular Expression Functions (POSIX Extended) : ereg


Regular expression match (PHP 4, PHP 5)
int ereg ( string pattern, string string [, array &regs] )

Example 1894. ereg() example

The following code snippet takes a date in ISO format (YYYY-MM-DD) and prints it in DD.MM.YYYY format:

if (ereg ("([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})", $date, $regs)) {
} else {
"Invalid date format: $date";

Related Examples ( Source code ) » ereg

Code Examples / Notes » ereg

joel weierman

While this is relatively simple example, I was unable find a clean method of doing this anywhere else, so I thought I would post it here.
As part of a file upload package, I wanted to prevent the uploading of double byte character filenames and other special ASCII characters that may not work well on a Windows and/or Linux system. Here is the statement I ended up using which seems to have done the trick.
ereg("[^a-zA-Z0-9._-]", $file_name)

'morgan'.'galpin'.chr 64 .'gmail'.'.com'

Try this version instead of the one previously posted.
   Returns an array containing each of the sub-strings from text that
   are between openingMarker and closingMarker. The text from
   openingMarker and closingMarker are not included in the result.
   This function does not support nesting of markers.
 function returnSubstrings($text, $openingMarker, $closingMarker) {
   $openingMarkerLength = strlen($openingMarker);
   $closingMarkerLength = strlen($closingMarker);
   $result = array();
   $position = 0;
   while (($position = strpos($text, $openingMarker, $position)) !== false) {
     $position += $openingMarkerLength;
     if (($closingMarkerPosition = strpos($text, $closingMarker, $position)) !== false) {
       $result[] = substr($text, $position, $closingMarkerPosition - $position);
       $position = $closingMarkerPosition + $closingMarkerLength;
   return $result;
 // Example:
 $exampleText = "<b>bonjour</b> à tous, <b>comment</b> allez-vous ?";
 $result = returnSubstrings($exampleText, "<b>", "</b>");
 // Prints:
 // array (
 //   0 => 'bonjour',
 //   1 => 'comment',
 // )


Save yourself some headache and time, don't use the \d (digits) \w (alphanumeric) and \s (whitespace) short forms. Not only do they make the code less readable, they don't seem to work with ereg.
Use [0-9], [A-Za-z0-9], [ \n\r\t] instead.
Since the regex example in this article is a bit on the complex side, I'll throw in a simpler regex example:
Say you want to validate valid variable names:
$regex_valid_variable_name = '^[A-Za-z_][A-Za-z0-9_]*$';
// ^ in this context means that the regex is anchored
// to the beginning of the string.
// A single [xxx] means that a single letter must mach
// the criteria within
// The [xxx]* means that [xxx] can mach from zero to
// unlimited times.
// The $ is another anchor, except it is for the end of
// the sting.
// Valid names: "_", "hello1", "a_variable"
// Invalid names: "4number", "five-to", "one two", " space "
//Test it out:
$regx = $regx_valid_variable_name;
$valid = array ( '_', 'hello1', 'a_variable' );
$invalid = array ( '4number', 'five-to', 'one two', ' space ');
foreach($valid as $v)
echo 'Valid '.(ereg($regx, $v) ? 'yes' : '<b>no</b>') . ": $v<br />\n";
foreach($invalid as $v)
echo 'Invalid '.(!ereg($regx, $v) ? 'yes' : '<b>no</b>') . ": $v<br />\n";


preg_match is much more faster then ereg, MUCH MORE faster.


On a small note to email checking:
Recently it is possible to register domains like www.kü
This would also mean that the IsEMail() function from "php at easy2sync dot com" would report an email address like "contact@kü" as false.
To correct this, use the function below:
function IsEMail($e)
(\.[a-z]{2,4})$", $e))
return TRUE;
return FALSE;


Ok well someone else posted this but if didn't work so I made my own.
I used this to check file names that are to be created on a server.
File names that start with a-Z or 0-9 and contain a-Z, 0-9, underscore(_), dash(-), and dot(.) will be accepted.
File names beginning with anything but a-Z or 0-9 will be rejected.
File names  containing anything other than above mentioned will also be rejected.
Here it is.
$result = ereg("(^[a-zA-Z0-9]+([a-zA-Z\_0-9\.-]*))$" , $filename);

psonice aat

I wanted a more strict check for UK postcodes, and decided to do it by stripping all whitespace then using ereg:
$pcode=str_replace(" ","",$in_post_code);
if (!ereg('^[a-zA-Z]{1,2}[0-9]{1,2}[a-zA-Z]{0,1}[0-9]{1}[a-zA-Z]{2}$', $pcode))
   return false;
Probably could be improved, as I've just started, but it matches everything listed on the post office spec.


I had problem using is_numeric() to verify if user inputs is a number (including optional floating sign and decimals).  Instead I found this expression from and modified it for a bit.
3.55      true
-3.55     true
+3.55    true
2456.90  true
34skd    false
23.      false
2dt6      false
Note: mine doesn't have the exponent part; for matching number with exponents, visit the site above :)


I could not find a definitive and 100% working function that validates the UK postcodes, so was forced to write one myself.
The authoritative source of information is
which I amended with the new postcode for Tristan da Cunha.
Here is the ugly beast (don't wanna see regexp's ever again):
function IsPostcode($postcode) {
 $postcode = strtoupper(str_replace(chr(32),'',$postcode));
."[0-9][ABD-HJLNP-UW-Z]{2})$", $postcode))
   return $postcode;
   return FALSE;


Here's a function i've created to return an array of each substring searched in a string.
function Return_Substrings($text, $sopener, $scloser)
               $result = array();
               $noresult = substr_count($text, $sopener);
               $ncresult = substr_count($text, $scloser);
               if ($noresult < $ncresult)
                       $nresult = $noresult;
                       $nresult = $ncresult;
               for ($i=0;$i<$nresult;$i++)
                       $pos = strpos($text, $sopener) + strlen($sopener);
                       $text = substr($text, $pos, strlen($text));
                       $pos = strpos($text, $scloser);
                       $result[] = substr($text, 0, $pos);
                       $text = substr($text, $pos + strlen($scloser), strlen($text));
               return $result;
Example :
   $string = "<b>bonjour</b> à tous, <b>comment</b> allez-vous ?";
   $result = Return_Substrings($string, "<b>", "</b>");


Here is a tutorial on regular expressions in PHP, which I needed to create ereg functions not covered in the snippets:


Here is a fixed version of the UK postcode check function by tomas at phusis dot co dot uk. There was a bug on line 2 of the reg expression where a closing square-bracket was doubled-up ("]]" which should've been "]").
function IsPostcode($postcode) {
 $postcode = strtoupper(str_replace(chr(32),'',$postcode));
."[0-9][ABD-HJLNP-UW-Z]{2})$", $postcode))
  return $postcode;
  return FALSE;


I think this is not clear:
"the matches will be stored in the elements of the array regs. $regs[1] will contain the substring which starts at the first left parenthesis; $regs[2] will contain the substring starting at the second, and so on. $regs[0] will contain a copy of the complete string matched. "
Beacause By "substring," it means the string contained within the parenthesis.
But in that statement it isn't so clearly
With regards
Amir Hossein Estakhrian

puremango dot co dot uk

for constructing regexes, I recommend
-it highlights the match as you type it!!!


After a lot of hard work I managed to create the following regular expression, which matches any HTML tag pair (i.e. opening and closing tag), as specified by tagname:
^(.*)(<[ \n\r\t]*tagname(>|[^>]*>))(.*)(<[ \n\r\t]*/[ \n\r\t]*tagname(>|[^>]*>))(.*)$
The expression is deliberately very forgiving of bad HTML - I wanted to match anything that could be reasonably accepted by a forgiving browser, rather than make it standards compliant. Whitespace is allowed between the tagname and the opening and closing tag symbols, and also between the / and the tagname for the closing tag.
For my own use, I have wrapped it in a function call, which you may find useful.  Here it is with a few notes. I hope somebody finds it useful.
- Mark Clements
function ereg_MatchedHTMLTags($tagname) {
return "^(.*)(<[ \\n\\r\\t]*$tagname(>|[^>]*>))(.*)(<[ \\n\\r\\t]*/[ \\n\\r\\t]*$tagname(>|[^>]*>))(.*)$";
// Use with eregi to ensure case-insensitive match.
// e.g. to split an HTML page based on body tag:
// eregi(ereg_MatchedHTMLTags('body'), $Source, $Matches)
// The following values will be held in $Matches
//(marked values are unintended byproducts of the expression)
//           *[0] - the entire string ($Source).
//            [1] - everything before the opening tag
//            [2] - the opening tag, including all contents (i.e. everything between < and >)
//           *[3] - the opening tag from end of the tag name,
//                      e.g. '<body bgcolor="#000000">' gives ' bgcolor="#000000">'
//            [4] - the tag contents (everything between the opening and closing tag)
//            [5] - the complete closing tag.
//           *[6] - the closing tag from the end of the tag name
//                      e.g. '</body invalid text>' gives ' invalid text>'
//            [7] - everything after the closing tag.

jason smart knarlin

A common mistake seems to be trying to escape characters within a bracket
expression. Unlike the preg functions, backslash is always taken literally
within a bracket expression using the ereg functions. See
for more details.
Some of the posts here can be re-written to be much simpler.
16-Feb-2005 10:02
attempts to allow square brackets in a string with
^[a-zA-Z0-9 [.[.] [.].] ]{1,}$
Although this appears to work a less confusing means is
The ] has to be the first character (after a possible ^) but the [ can be
anywhere as long as it is not in the middle of a range of course.
09-Apr-2005 11:52
Says that ereg("hi[:space:]*bob", $string)
doesnt work in php 4 and to use preg_match() instead.
The above quoted use is incorrect it should be
<?php ereg("hi[[:space:]]*bob", $string); ?>
I tested this with the following in php 4.3.3 and it works fine
//The hex codes are space, tab, line feed, vertical tab, form feed, carriage return
$whitespace = "\x20\x09\x0a\x0b\x0C\x0d";
$teststring = "hi".$whitespace."bob";
$result = ereg ("hi[[:space:]]*bob", $teststring, $arr);
echo ('Matches '.$result.' characters');
//Prints Matches 11 characters
23-May-2005 08:22
Says that ereg("^[' A-Za-Z]+$", $cardName); will not work.
The fault with the above is the range a-Z the capital Z comes before small a
and so this will fail. The following works fine
$cardname = "John 'Doe'";
$result = ereg("^[' A-Za-z]+$", $cardname, $arr);
echo ('Matches '.$result.' characters');
//Prints Matches 10 characters
09-Sep-2005 11:01
Tries to escape with \ in a bracket expression
You cannot with ereg functions (preg you can) so
ereg("^([-a-zA-Z0-9_\.\!@#\$&\*\+\=\|])*$" , $var)
should be
<?php ereg("^([-a-zA-Z0-9_.!@#$&*+=|])*$", $var); ?>

Change Language

Follow Navioo On Twitter
eXTReMe Tracker