preg_match is much more faster then ereg, MUCH MORE faster.
ereg
(PHP 4, PHP 5)
ereg — 正規表現にマッチさせる
説明
int ereg ( string $pattern, string $string [, array &$regs] )注意: Perl 互換の正規表現構文を使用する preg_match() のほうが、多くの場合 ereg() よりも速く動作します。
この関数は、pattern で指定した正規表現 により大文字小文字を区別して string を検索します。
pattern の括弧でくくられた部分文字列に マッチし、かつこの関数が 3 番目の引数 regs を 指定してコールされた場合、マッチした部分が配列 regs に格納されます。$regs[1] は最初の左括弧が始まる部分文字列を保持、 $regs[2] は二番目の左括弧が始まる部分文字列を保持、 といったようになっています。$regs[0] は マッチした文字列全体のコピーを保持しています。
注意: PHP 4.1.0 以前(4.1.0 を含む)のバージョンでは、$regs にはちょうど 10 個の要素が代入されました。これは、実際にマッチした 括弧付きのサブ文字列が 10 より多くても少なくても同じでした。ただし、 ereg() にはより多くの部分文字列にマッチする 能力があります。マッチするものが見付からなかった場合、 $regs は、ereg() により 書き換えられません。
string の中で pattern がマッチした場合にはマッチした文字列の長さを返し、マッチしなかった場合 またはエラーとなった場合は FALSE を返します。 オプションのパラメータ regs が渡されなかったり マッチした文字列の長さが 0 だったりした場合は、この関数は 1 を返します。
以下のサンプルコードは、ISO フォーマット(YYYY-MM-DD) で格納されている 日付を DD.MM.YYYY フォーマットで表示するものです。
例 1845. ereg() の例
<?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";
}
?>
eregi()、ereg_replace()、 eregi_replace()、preg_match()、 strpos() および strstr() も参照ください。
ereg
29-Jul-2007 08:31
12-Jul-2007 05:26
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";
?>
10-Jun-2007 07:49
Here is a tutorial on regular expressions in PHP, which I needed to create ereg functions not covered in the snippets:
http://www.zend.com/zend/spotlight/code-gallery-wade5.php
01-Sep-2006 12:41
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;
}
?>
19-Aug-2006 11:00
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);
?>
07-Jun-2006 12: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;
}
?>
12-May-2006 05:16
Try this version instead of the one previously posted.
<?php
/**
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>");
var_export($result);
// Prints:
// array (
// 0 => 'bonjour',
// 1 => 'comment',
// )
?>
21-Mar-2006 11: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>");
?>
15-Mar-2006 06: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.
15-Dec-2005 08: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 :)
16-Nov-2005 12: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
16-Oct-2005 05: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
//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); ?>
19-Jul-2005 10:34
for constructing regexes, I recommend
http://www.weitz.de/regex-coach/
-it highlights the match as you type it!!!
23-Jun-2005 04: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)
23-Jun-2005 03: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;
}
27-Apr-2005 11: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(>|[^>]*>))(.*)$";
}
// 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.
?>