|
 |
ereg (PHP 3, PHP 4, PHP 5) ereg -- Regular expression match Descriptionint ereg ( string pattern, string string [, array ®s] ) Замечание:
preg_match(), which uses a Perl-compatible
regular expression syntax, is often a faster alternative to
ereg().
Searches a string for matches to the regular
expression given in pattern in a case-sensitive
way.
If matches are found for parenthesized substrings of
pattern and the function is called with
the third argument regs, 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.
Замечание:
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().
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.
The following code snippet takes a date in ISO format
(YYYY-MM-DD) and prints it in DD.MM.YYYY format:
Пример 1. ereg() example
<?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";
}
?>
|
|
See also eregi(), ereg_replace(),
eregi_replace(), preg_match(),
strpos(), and strstr().
ereg
tomas at phusis dot co dot uk
06-Jun-2006 08:41
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;
}
?>
petfrogg at hotmail dot com
12-May-2006 03:06
According to the manual the usage of regexps are slower then build in functions. I was faced with the need of a conf-file in order to confirm to the company standard and in order to fix this I needed to parse strings and automaticly set the correct “type” of every type fetched from the conf-file as strings. I’ve red some examples of this using eregs but none worked for me. This is my working solution:
function _setType($mValue){
$mReturnData = trim($mValue);
switch($mReturnData){
case strtolower($mReturnData)== 'true':
$mReturnData = true;
break;
case strtolower($mReturnData)== 'false':
$mReturnData = false;
break;
case strtolower($mReturnData)== 'null':
$mReturnData = null;
break;
case is_numeric($mReturnData):
if($mReturnData == (integer)$mReturnData){
$mReturnData = (integer)$mReturnData;
}else{
$mReturnData = (float)$mReturnData;
}
break;
default:
$mReturnData = $mReturnData;
}
return $mReturnData;
}
Hope it will help someone.
'morgan'.'galpin'.chr(64).'gmail'.'.com'
11-May-2006 01:16
Try this version instead of the one previously posted.
<?php
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;
}
$exampleText = "<b>bonjour</b> à tous, <b>comment</b> allez-vous ?";
$result = returnSubstrings($exampleText, "<b>", "</b>");
var_export($result);
?>
info at orgied dot com
21-Mar-2006 06:54
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>");
?>
psonice (aat) gmail.com
14-Mar-2006 01:39
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.
Tristan Scott - trs998 at gmail dot com
13-Mar-2006 08:15
ereg("^[a-zA-Z]{1,2}((\d{1,2})|(\d{1}[a-zA-Z]{1}))[ ]?\d{1}[a-zA-Z]{2}$")
Should check for valid postcodes in the uk.
Note: this will not match GIR 0AA, whcih is in use but doesn't follow the post office rules. also, this is not strict... some invalid postcodes are permitted some letters do not appear in some positions. It will, however, match:
AN NAA
ANN NAA
AAN NAA
AANN NAA
ANA NAA
AANA NAA
odnowa-sql at o2 dot pl
24-Feb-2006 10:28
I would like to inform you about a bug-like thingy which I've seen when trying to convert BBcode [url][/url] tags to HTML <a href=''></a> tag. This was my code:
$vn = ereg_replace("\\[url=([^\[]*)\\]([^\[]*)\\[/url\\]","<a href='http://\\1'>\\2</a>",$vn);
It looks a bit complicated, look closer at the following part of above line:
[^\[]
You will probably notice ONE backslash instead of two, but it really worked when I was trying to match everything except [ character. And the [^\\[] sequence did not work. So, when you are placing a negated bracket, escape it by ONE backslash.
Hup2.com
07-Feb-2006 03:35
if anyone needs the code to validate a uk postcode I have included it below:
// check post code is in correct format
if (!ereg("^[A-Z]{1,2}[0-9]{1,2}[[:space:]][0-9]{1}[A-Z]{2}", strtoupper($postcode))) {
print "You need to enter a valid post code!<br/><br/>";
}
Hope this helps someone
Chris
ar_cat at shaw dot ca
14-Dec-2005 03:13
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 :)
net_navard at yahoo dot com
15-Nov-2005 07:35
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
bnewbold at codegreene dot com
03-Nov-2005 02:36
mcallier at gmail dot com's expression for zip codes is still wrong.
"^[0-9]{5}(-[0-9]{4})*$" will call the following zip codes good:
91425
91425-3444
91425-3444-3455
91425-3444-3455-4556
(etc)
the star (*) in the expression means zero or more.
Instead it should be a question mark (?) meaning zero or one only.
use "^[0-9]{5}(-[0-9]{4})?$"
Jason Smart knarlin at yahoo dot com dot au
16-Oct-2005 01:13
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
$whitespace = "\x20\x09\x0a\x0b\x0C\x0d";
$teststring = "hi".$whitespace."bob";
$result = ereg ("hi[[:space:]]*bob", $teststring, $arr);
echo ('Matches '.$result.' 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');
?>
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); ?>
mcallier at gmail dot com
04-Oct-2005 01:21
I think that fox's zip code check may need a slight modification. Here is fox's code:
$error_code=(ereg("^[0-9]{5}(-[0-9]{4})$",$zip))? NULL:1;
This will error on valid zipcodes such as 99212. If you change the regular expression to:
$error_code=(ereg("^[0-9]{5}(-[0-9]{4})*$",$zip))? NULL:1;
It will not error on valid zipcodes such as 99212.
To test this you may use the following code:
<?php
$testzip[]="99212";
$testzip[]="9921";
$testzip[]="99212-1234";
$testzip[]="9921a";
$testzip[]="99212-12";
$regex['fox']="^[0-9]{5}(-[0-9]{4})$";
$regex['mcallier']="^[0-9]{5}(-[0-9]{4})*$";
foreach($regex as $key=>$expression)
{
echo($key."<br>\n");
echo("-----------<br>\n");
foreach($testzip as $value)
{
$test=ereg($expression,$value);
$test==1?$test="good":$test="bad";
echo("$value=$test<br>\n");
}
echo("<br>\n");
}
?>
The output of this is:
fox
-----------
99212=bad
9921=bad
99212-1234=good
9921a=bad
99212-12=bad
mcallier
-----------
99212=good
9921=bad
99212-1234=good
9921a=bad
99212-12=bad
Jason knarlin at yahoo dot com dot au
02-Oct-2005 11:19
A previous post stated "Beware that eregs in PHP4 are broken, for instance if you want to match "a to z, 0,9 and -" you might want to use [a-z0\-9] but it will silently fail due to a bug"
This is incorrect, this is not a bug, nor is ereg broken on this count!
In my testing of ereg, matching `-' `[' or `]' within a bracketed expression ereg works exactly according to the regex man page http://www.tin.org/bin/man.cgi?section=7&topic=regex referred from the php manual page at http://au3.php.net/manual/en/ref.regex.php
From the regex man page you will find that within a bracketed expression to match a literal `]' make it the first character (following a possible `^'). To include a literal `-' make it the first or last character, or the second endpoint of a range. To use a literal `-' as the first endpoint of a range, enclose it in `[.' and `.]'
spook says
if you want a string to work that matches "a to z", "A to Z", "0 to 9", "-", "[", "]" and "_" you will have to use this expression:
([0-9a-zA-Z_]|\-|\[|\])
end spook says
A neater solution is
[]0-9a-zA-Z_[-]
I hope this settles that ereg is not buggy or broken in this regard
(I reposted as the preview on this board misled me, I thought I had to escape \ )
Jason knarlin at yahoo dot com dot au
02-Oct-2005 09:48
A previous post stated "Beware that eregs in PHP4 are broken, for instance if you want to match "a to z, 0,9 and -" you might want to use [a-z0\\-9] but it will silently fail due to a bug"
This is incorrect, this is not a bug, nor is ereg broken on this count!
In my testing of ereg, matching `-' `[' or `]' within a bracketed expression ereg works exactly according to the regex man page http://www.tin.org/bin/man.cgi?section=7&topic=regex referred from the php manual page at http://au3.php.net/manual/en/ref.regex.php
From the regex man page you will find that within a bracketed expression to match a literal `]' make it the first character (following a possible `^'). To include a literal `-' make it the first or last character, or the second endpoint of a range. To use a literal `-' as the first endpoint of a range, enclose it in `[.' and `.]'
spook says
if you want a string to work that matches "a to z", "A to Z", "0 to 9", "-", "[", "]" and "_" you will have to use this expression:
([0-9a-zA-Z_]|\\-|\\[|\\])
end spook says
A neater solution is
[]0-9a-zA-Z_[-]
I hope this settles that ereg is not buggy or broken in this way
eregitate
09-Sep-2005 06:01
It was really hard for me to get the next checker!!!
I think the information displayed here is really scarce.
I had to get a PHP book to get the following information:
to indicate the start of a string : ^, nothing comes before it
you'll need to escape the following characters (with a backslash \ ) :
. \ ! + * ? [ ] ^ $ ( ) = ! < > | and :
the characters above each have a special meaning,
that's why you need to escape them to include them in a string.
* means : match this pattern 0 or more times
? means : match this pattern exactly 1 time
+ means : match this pattern 1 or more times
and $ means the definite end of a string, nothing may come afterward.
With this information I could finaly check a complete string containing only a few allowed character types :
ereg("^([-a-zA-Z0-9_\.\!@#\$&\*\+\=\|])*$" , $var)
some of the other tips here let other character through like < and >,
which I did not want to get past my check! Hope this helps out.
chrismax2u at yahoo dot com dot cn
02-Sep-2005 01:15
use ereg() and checkdate()
$input_date="2005-09-02";
//check date with ereg()
if (!ereg("^(20[0-9]{2})-(0[1-9]|1[0-2])-([12][0-9]|3[01])$",
$input_date))
{
echo "<script>alert(\"pass!\")</script>";
}
//check date with checkdate()
$explode_date=explode("-",$input_date);
if (!checkdate($explode_date['1'],$explode_date['2'],
$explode_date['0']))
{
echo "<script>alert(\"stop!\")</script>";
exit;
}
fox
10-Aug-2005 08:13
concerning the 'valid postal code' bit from 25 july -
regular expressions are good for turning the longer zip checking code given below into much shorter snippets, such as the following (which accomplishes the same zip code check):
$error_code=(ereg("^[0-9]{5}(-[0-9]{4})$",$zip))? NULL:1;
the expression requires the first five digits and allows an additional four; the hyphen is required if the optional four are present
Joel Weierman
22-Jun-2005 12:56
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)
irlkersten at gmail dot com
22-Jun-2005 11:54
On a small note to email checking:
Recently it is possible to register domains like www.kche.de
This would also mean that the IsEMail() function from "php at easy2sync dot com" would report an email address like "contact@kche.de" as false.
To correct this, use the function below:
function IsEMail($e)
{
if(eregi("^[a-zA-Z0-9]+[_a-zA-Z0-9-]*
(\.[_a-z0-9-]+)*@[a-z0-9]+
(-[a-z0-9]+)*(\.[a-z0-9-]+)*
(\.[a-z]{2,4})$", $e))
{
return TRUE;
}
return FALSE;
}
23-May-2005 03:22
I am trying to use ereg to validate a credit card name, and all I want it to do is make sure that letters, spaces and apostrophes are allowed. ereg("^[' A-Za-Z]+$", $cardName);
This did not work as I expected it too, in fact I could not enter even enter all letters ?
php at REMOVEMEkennel17 dot co dot uk
26-Apr-2005 07:00
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(>|[^>]*>))(.*)$";
}
?>
kitchen -at- script kitchen -dot- com
08-Apr-2005 06:52
just to note here, php4's ereg() doesn't support [:space:], so if you want to match arbitrary whitespace, use preg_match()
$string = "hi \t bob";
if (ereg("hi[:space:]*bob", $string)) {
print "you must be using php5!\n";
}
// php4 version
if (preg_match("/hi\s*bob/",$string)) {
print "works in both php4 and php5!\n";
}
php5's ereg() does support [:space:]
alcator at seznam dot cz
11-Mar-2005 11:47
Reaction to:
(19[0-9]{2}|20[0-5]{2})-(0[0-9]|1[0-2])-([12][0-9]|3[01])
--> There is more problems than just "this will validate 2005-02-31". The worse problem is that it WON'T validate 2001-01-01...
(19[0-9]{2}|200[0-5]{1})-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])
(Note that "00" is no longer possible for days and months, while allowing for 01..09...)
Still, it doesn't protect against non-existent dates.
LIX
01-Mar-2005 02:13
It's important to know - when you use
[0-9]{4})-([0-9]{2})-([0-9]{2}
to valid date in YYYY-MM-DD format then script accepts dates etc. 20005-02-035
You can use
^[0-9]{4})-([0-9]{2})-([0-9]{2}$
to valid regular date format YYYY-MM-DD.
24-Feb-2005 12:17
The date example above is still a little dodgey as this:
(19[0-9]{2}|20[0-5]{2})-(0[0-9]|1[0-2])-([12][0-9]|3[01])
will allow invalid dates such as
1900-00-31
Just a small correction is needed (IMO), switching a 0 for a 1:
(19[0-9]{2}|20[0-5]{2})-(0[1-9]|1[0-2])-([12][0-9]|3[01])
^
Of course invalid dates such as 31st feb are still possible.
punkpuke at comcast dot net
15-Feb-2005 04:02
This took me a little to find out, but from one PHP/Regex newb to another if your trying to let people use Square Brackets in a string: [ ]
Like in this string for example: ^[a-zA-Z0-9]{1,}$
This following will most likely not work (You can't backslash them): ^[a-zA-Z0-9\[\]]{1,}$
So, to escape the Square Brackets, use the following to delimit collating symbols:
[. Special Character Goes Here .]
So The New Expression: ^[a-zA-Z0-9 [.[.] [.].] ]{1,}$ (I spaced it so it was less confusing)
Carrajola
11-Feb-2005 10:54
Since the example has the purpose of validating the date in $date and not just change it, the regular expression is not accurate, because a date like 0000-00-00 is validated.
It should be something like this:
(19[0-9]{2}|20[0-5]{2})-(0[0-9]|1[0-2])-([12][0-9]|3[01])
this regular expression is still not totally correct because it's not sensible to a impossible date like 2005-02-31.
| |