ereg
(PHP 4, PHP 5)
ereg — Regular expression match
Description
$pattern
, string $string
[, array &$regs
] )
Searches a string
for matches to the regular
expression given in pattern
in a case-sensitive
way.
This function has been DEPRECATED as of PHP 5.3.0. Relying on this feature is highly discouraged.
Parameters
-
pattern
-
Case sensitive regular expression.
-
string
-
The input string.
-
regs
-
If matches are found for parenthesized substrings of
pattern
and the function is called with the third argumentregs
, the matches will be stored in the elements of the arrayregs
.$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.
Return Values
Returns the length of the matched string if a match for
pattern
was found in string
,
or FALSE
if no matches were found or an error occurred.
If the optional parameter regs
was not passed or
the length of the matched string is 0, this function returns 1.
Changelog
Version | Description |
---|---|
4.1.0 | Up to (and including) PHP 4.1.0 $regs will be filled with exactly ten elements, even though more or fewer than ten parenthesized substrings may actually have matched. This has no effect on ereg()'s ability to match more substrings. If no matches are found, $regs will not be altered by ereg(). |
Examples
Example #1 ereg() example
The following code snippet takes a date in ISO format (YYYY-MM-DD) and prints it in DD.MM.YYYY format:
<?php
if (ereg ("([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})", $date, $regs)) {
echo "$regs[3].$regs[2].$regs[1]";
} else {
echo "Invalid date format: $date";
}
?>
Notes
Note:
As of PHP 5.3.0, the regex extension is deprecated in favor of the PCRE extension. Calling this function will issue an
E_DEPRECATED
notice. See the list of differences for help on converting to PCRE.
ereg() is deprecated as of PHP 5.3.0. preg_match() is the suggested alternative to this function.
See Also
- eregi() - Case insensitive regular expression match
- ereg_replace() - Replace regular expression
- eregi_replace() - Replace regular expression case insensitive
- preg_match() - Perform a regular expression match
- strpos() - Find the position of the first occurrence of a substring in a string
- strstr() - Find the first occurrence of a string
- quotemeta() - Quote meta characters
Коментарии
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
<?php
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.
?>
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)
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
http://php.planetmirror.com/manual/en/function.eregi.php#57824
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
^[]a-zA-Z0-9[]{1,}$
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
<?php
//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
<?php
$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); ?>
Hello
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
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 http://www.regular-expressions.info/floatingpoint.html and modified it for a bit.
^[+-]?[0-9]*\.?[0-9]+$
/*
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 wanted a more strict check for UK postcodes, and decided to do it by stripping all whitespace then using ereg:
<?php
$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.
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;
else
$nresult = $ncresult;
unset($noresult);
unset($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>");
?>
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
http://www.govtalk.gov.uk/gdsc/html/frames/PostCode.htm
which I amended with the new postcode for Tristan da Cunha.
Here is the ugly beast (don't wanna see regexp's ever again):
<?php
function IsPostcode($postcode) {
$postcode = strtoupper(str_replace(chr(32),'',$postcode));
if(ereg("^(GIR0AA)|(TDCU1ZZ)|((([A-PR-UWYZ][0-9][0-9]?)|"
."(([A-PR-UWYZ][A-HK-Y]][0-9][0-9]?)|"
."(([A-PR-UWYZ][0-9][A-HJKSTUW])|"
."([A-PR-UWYZ][A-HK-Y][0-9][ABEHMNPRVWXY]))))"
."[0-9][ABD-HJLNP-UW-Z]{2})$", $postcode))
return $postcode;
else
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.
<?php
$result = ereg("(^[a-zA-Z0-9]+([a-zA-Z\_0-9\.-]*))$" , $filename);
?>
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 "]").
<?php
function IsPostcode($postcode) {
$postcode = strtoupper(str_replace(chr(32),'',$postcode));
if(ereg("^(GIR0AA)|(TDCU1ZZ)|((([A-PR-UWYZ][0-9][0-9]?)|"
."(([A-PR-UWYZ][A-HK-Y][0-9][0-9]?)|"
."(([A-PR-UWYZ][0-9][A-HJKSTUW])|"
."([A-PR-UWYZ][A-HK-Y][0-9][ABEHMNPRVWXY]))))"
."[0-9][ABD-HJLNP-UW-Z]{2})$", $postcode))
return $postcode;
else
return FALSE;
}
?>
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:
<?php
$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";
?>
This is a date regexp that I made to allow different combinations of month, day, and year. it's rather long but it works.
(^([0-3]{0,1})([1-9]{1,1})([\-]{1,1})(([1]{1,1})([0-2]{1,1})|
([0]{0,1})([1-9]{1,1}))([\-]{1,1})([1-2]{1,1})(\d{3})$)|
(^(([1]{1,1})([0-2]{1,1})|([0]{0,1})([1-9]{1,1}))([\-]{1,1})
([0-3]{0,1})([1-9]{1,1})([\-]{1,1})([1-2]{1,1})(\d{3})$)|
(^([1-2]{1,1})(\d{3})([\-]{1,1})(([1]{1,1})([0-2]{1,1})|
([0]{0,1})([1-9]{1,1}))([\-]{1,1})([0-3]{0,1})([1-9]{1,1})$)
yyyy-mm-dd, mm-dd-yyyy, dd-mm-yyyy
2007-02-05
12-25-2007
25-02-2007
2-5-2007
25-2-2007
2007-9-23
09-06-2007
09-23-2007
The above will check valid
Anything not in one of the combinations of dd,mm,yyyy formats above will fail.
these will also fail
2007-32-12
13-22-2007
0-1-2007
1-0-2007
Any sugestions on making it smaller and more efficients would be appreciated.
This is a fix for days over 31 and shorter version
^(([1]{1}[0-2]{1}|[0]{0,1}[1-9]{1})[\-]{1}([0-2]{0,1}\d{1|
[3]{1,1}[0-1]{1})[\-]{1}[1-2]{1}\d{3}|([0-2]{0,1}\d{1}|
[3]{1,1}[0-1]{1})[\-]{1}([1]{1}[0-2]{1}|[0]{0,1}[1-9]{1})
[\-]{1}[1-2]{1}\d{3}|[1-2]{1}\d{3}[\-]{1}([1]{1}[0-2]{1}|
[0]{0,1}[1-9]{1})[\-]{1}([0-2]{0,1}\d{1}|[3]{1,1}[0-1]{1}))$
There is undocumented behaviour for this command!
You cannot check for strings of 1-256 characters or longer.
For example, this will evaluate to true:
ereg("^[a-zA-Z0-9' ]{1,255}$","ghfhg");
But this will give the error:
PHP Warning: ereg(): REG_BADBR
ereg("^[a-zA-Z0-9' ]{1,256}$","ghfhg");
PHP version (on Windows XP):
PHP 5.2.5 (cli) (built: Nov 8 2007 23:18:51)
Copyright (c) 1997-2007 The PHP Group
Zend Engine v2.2.0, Copyright (c) 1998-2007 Zend Technologies
It's important to note for certain regular expression that your $regs[] array will only contain as many values as you have sets of parenthesis in your regexp. (plus 1, of course) For example, the regexp below was designed to locate tags enclosed in <> characters inside a string:
<?php ereg("^([^<]*)(<[^>]+>[^<]*)*$", $str, $tags) ?>
This will *not* create an arbitrarily long array in $tags for the number of tags that it finds. Given the string "This <has> a <couple> of <tags> in it", you'll see:
0 : This <has> a <couple> of <tags> in it
1 : This
2 : <tags> in it
Since the same parenthesized section of the regexp is matching all tags found, it overwrites the same section of the array. If you try increasing the number of parenthesis, it just creates duplicates of the same result.
<?php
function fractionstr2decimal($fs){
if (is_numeric($fs)){
return $fs;
} elseif (ereg ("([0-9]{1,6}[ ])?([0-9]{1,6})\/([0-9]{0,6}[1-9][0-9]{0,6})", $fs, $regs)) {
/* ({1-6 digits}space optional) {1-6 digits}/(1-13 digits with at least one digit not 0 )*/
return ($regs[1]+$regs[2]/$regs[3]);
} else {
return (NULL); /* Invalid Fraction */
}
}
echo fractionstr2decimal("1024 5/132")."<br>"; /* 1024.0378787879 */
echo fractionstr2decimal("23")."<br>"; /* 23 */
$i=fractionstr2decimal("1 2/3");
echo "<br>$i"; /* 1.66666666666667 */
if ($i and $i<=1 ) echo "<1<br>"; /* */
$i=fractionstr2decimal("2/3");
echo "<br>$i"; /* 0.66666666666667 */
if ($i and $i<=1 ) echo "<1<br>"; /* <1 */
$i=fractionstr2decimal("2/0");
echo "<br>$i";
if ($i and $i<=1 ) echo "<1<br>";
?>
UK postcode validation.
We've used the expression put forward by tomas and jaik,
but we found that it fails on Coventry (CV) postcodes.
Here is an alternative that works for these postcodes and
also adds support for the Overseas Territories like Tristan da Cunha.
<?php
function IsPostcode($postcode) {
$postcode = strtoupper($postcode);
if(ereg("((GIR 0AA)|(TDCU 1ZZ)|(ASCN 1ZZ)|(BIQQ 1ZZ)|(BBND 1ZZ)"
."|(FIQQ 1ZZ)|(PCRN 1ZZ)|(STHL 1ZZ)|(SIQQ 1ZZ)|(TKCA 1ZZ)"
."|[A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]"
."|[A-HK-Y][0-9]([0-9]|[ABEHMNPRV-Y]))"
."|[0-9][A-HJKS-UW]) [0-9][ABD-HJLNP-UW-Z]{2})", $postcode)) {
return $postcode;
} else {
return FALSE;
}
}
?>
In reply to Francis,
Your regular expression:
$pattern = "^(\()?([0-9]{3})(\))?( )?([0-9]{3})( )?(\-)?( )?([0-9]{4})$";
I actually used this to validate a phone number. The one discrepancy I found is with patterns such as 503-555-1212, 503-5551212, [503]5551212, and every other pattern that does not have single whitespace or a dash as a delimiter, ereg() will return false when given your expression.
Based on your pattern, I came up with a more general and concise version making use of the dot meta-character:
$pattern = "^.?[0-9]{3}.?.?[0-9]{3}.?[0-9]{4}$";
When passed to ereg(), it will return "true" so long as there is 10 digits, regardless of the delimiter chosen by the user.
[503] 5551212 //true
5035551212 //true
503+555 1212//true
$pattern = "^(\()?([0-9]{3})(\))?( )?([0-9]{3})( )?(\-)?( )?([0-9]{4})$";
Here is a series of useful regular expressions.
<?php
function isValid($type,$var) {
$valid = false;
switch ($type) {
case "IP":
if (ereg('^([0-9]{1,3}\.){3}[0-9]{1,3}$',$var)) {
$valid = true;
}
break;
case “URL”:
if (ereg("^[a-zA-Z0-9\-\.]+\.(com|org|net|mil|edu)$",$var)) {
$valid = true;
}
break;
case “SSN”:
if (ereg("^[0-9]{3}[- ][0-9]{2}[- ][0-9]{4}|[0-9]{9}$",$var)) {
$valid = true;
}
break;
case “CC”:
if (ereg("^([0-9]{4}[- ]){3}[0-9]{4}|[0-9]{16}$",$var)) {
$valid = true;
}
break;
case “ISBN”:
if (ereg("^[0-9]{9}[[0-9]|X|x]$",$var)) {
$valid = true;
}
break;
case “Date”:
if (ereg("^([0-9][0-2]|[0-9])\/([0-2][0-9]|3[01]|[0-9])\/[0-9]{4}|([0-9][0-2]|[0-9])-([0-2][0-9]|3[01]|[0-9])-[0-9]{4}$",$var)) {
$valid = true;
}
break;
case “Zip”:
if (ereg("^[0-9]{5}(-[0-9]{4})?$",$var)) {
$valid = true;
}
break;
case "Phone":
if (ereg("^((\([0-9]{3}\) ?)|([0-9]{3}-))?[0-9]{3}-[0-9]{4}$",$var)) {
$valid = true;
}
break;
case “HexColor”:
if (ereg('^#?([a-f]|[A-F]|[0-9]){3}(([a-f]|[A-F]|[0-9]){3})?$',$var)) {
$valid = true;
}
break;
case “User”:
if (ereg("^[a-zA-Z0-9_]{3,16}$",$var)) {
$valid = true;
}
break;
}
return $valid;
}
#Example:
$phone = "789-1234";
if (isValid("Phone",$phone)) {
echo "Valid Phone Number";
} else {
echo "Invalid Phone Number";
}
?>
Hi,
for those looking for email adress PHP validation,
isemail is a javascrit function that checks the following conditions for the email string:
• only one @ sign permitted
• domain extension separator (.) must come after the @ symbol
• must be at least 2 characters (letters) after the domain extension separator (.)
• rejects all illegal characters including spaces.
• Allows only numbers, letters, the underscore (_) and the dash (-) character as valid input
(excluding the mandatory "@" and "." symbols).
• Minimum of 6 characters
The following pattern satisfy all-in-one for the ereg function:
$pattern = "^([A-Za-z0-9\.|-|_]{1,60})([@])";
$pattern .="([A-Za-z0-9\.|-|_]{1,60})(\.)([A-Za-z]{2,3})$";
ereg($pattern,$email)
Recognizing E-mail Addresses
worth noting: a valid e-mail may contain a + character.
for example:
if you send e-mail to myemail+something@gmail.com, gmail reroutes it to the account myemail@gmail.com. This is a useful feature, and it is very frustrating when websites that take your e-mail don't allow you to do this.
Here a little clear and easy script
that I wrote to validate an E-Mail Input.
I tried to understand ereg,
but the describtion on php.net did not help me,
so I made some research and finally (think)
that Im sure how to use ereg.
The following function works for me well and allows
an E-Mail to contain the following characters:
"A-Z, a-z, 0-9, . , - , _ "
<?php
function validateMail($mail) {
if($mail !== "") {
if(!ereg("^[A-Za-z0-9\.|-|_]*
[@]{1}[A-Za-z0-9\.|-|_]*[.]{1}[a-z]{2,5}$", $mail)) {
echo "wrong Input for E-Mail";
$mail ="";
return $mail;
}
else {
return $mail;
}
}
}
?>
to make it clear:
^ means begin here (startpoint of ereg)
$ means end here (endpoint of ereg)
* stand for endless characters (I want A-Z, a-z, 0-9 and the other characters to apear from 0 to endless
optional you can write {1,5} for
min 1 times a character or max 5 times a
characters instead of *
{1,2} means min 1 time a character and max 2 times a character (optional you can write * intead of {1,2}
{1} stand for max 1 time a character
\ means from here special characters (like .-_$ and so on)
| means OR
eregi & preg_match() what difference
Find page title
------------------
This handy code snippet will find and print the text within the <title> and </title> tags of a html page.
Find_ page_ title_by_eregi.php
----------------------------------
<?php
$fp = fopen("http://www.w3schools.com/default.asp","r");
while (!feof($fp) ){
$page .= fgets($fp, 4096);
}
$titre = eregi("<title>(.*)</title>",$page,$regs);
// reg exp is without / / and flexible
print_r($regs);
echo "<br/>";
// Array ( [0] => [1] => W3Schools Online Web Tutorials )
echo $regs[1] ;
// W3Schools Online Web Tutorials
fclose($fp);
?>
======================================
Find_ page_ title _by_preg_match_all.php
-----------------------------------------------
<?php
$fp = fopen("http://www.w3schools.com/default.asp","r");
while (!feof($fp) ){
$page .= fgets($fp, 4096);
}
preg_match_all("/<title>(.*)<\/title>/i",$page,$regs);
// reg exp must with / / and not flexible
print_r($regs);
echo "<br/>";
// Array ( [0] => Array ( [0] => ) [1] => Array ( [0] => W3Schools Online Web Tutorials ) )
echo $regs[1][0];
// W3Schools Online Web Tutorials
fclose($fp);
?>
"If the optional parameter regs was not passed or the length of the matched string is 0, this function returns 1."
This is very confusing. Reads as ereg() will always return 1 if you don't pass the OPTIONAL parameter. If that was the case, the parameter wouldn't be optional as the function would be completly useless without it. Of course the function ereg() still returns 0 if no match was found.