ereg

(PHP 3, PHP 4, PHP 5)

ereg -- 正则表达式匹配

说明

bool ereg ( string pattern, string string [, array regs] )

注: 使用 Perl 兼容正则表达式语法的 preg_match() 函数通常是比 ereg() 更快的替代方案。

以区分大小写的方式在 string 中寻找与给定的正则表达式 pattern 所匹配的子串。

如果找到与 pattern 中圆括号内的子模式相匹配的子串并且函数调用给出了第三个参数 regs,则匹配项将被存入 regs 数组中。$regs[1] 包含第一个左圆括号开始的子串,$regs[2] 包含第二个子串,以此类推。$regs[0] 包含整个匹配的字符串。

注: 直到 PHP 4.1.0 为止,$regs 将被填充为正好十个单元,即使实际匹配的子串少于十个。这并不影响 ereg() 匹配更多子串的能力。如果没有找到匹配,则 $regs 不会被 ereg() 更改。

如果在 string 中找到 pattern 模式的匹配则返回 TRUE,如果没有找到匹配或出错则返回 FALSE

以下代码片断接受 ISO 格式的日期(YYYY-MM-DD)然后以 DD.MM.YYYY 格式显示:

例子 1. 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()


add a note add a note User Contributed Notes
jaik at fluidcreativity dot co dot uk
31-Aug-2006 11: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;
}
?>
theppg_001 at hotmail dot com
19-Aug-2006 10: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);
?>
tomas at phusis dot co dot uk
06-Jun-2006 11: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 06: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. Ive 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'
12-May-2006 04: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',
  // )
?>
info at orgied dot com
21-Mar-2006 10: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
15-Mar-2006 05: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
14-Mar-2006 12: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
25-Feb-2006 02: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.
bob_at_drenai_dot_com
23-Feb-2006 10:13
Not quite right on the postcode validation...

Check the standards at

http://www.govtalk.gov.uk/gdsc/html/frames/PostCode.htm
Hup2.com
07-Feb-2006 07: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
15-Dec-2005 07: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 11: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
04-Nov-2005 06: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 04: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); ?>
mcallier at gmail dot com
05-Oct-2005 04: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
03-Oct-2005 02: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
03-Oct-2005 12: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 09: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 04: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 11: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
puremango dot co dot uk at gmail dot com
19-Jul-2005 09:34
for constructing regexes, I recommend

http://www.weitz.de/regex-coach/

-it highlights the match as you type it!!!
Joel Weierman
23-Jun-2005 03: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
23-Jun-2005 02: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 06: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 ?
berndt at michael berndt dot de
29-Apr-2005 09:23
extract various array elements with ereg()
http://www.michael-berndt.de/ie/tux/BerndtSector.htm
php at REMOVEMEkennel17 dot co dot uk
27-Apr-2005 10: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.

?>
kitchen -at- script kitchen -dot- com
09-Apr-2005 09: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
12-Mar-2005 03: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.
Candle1deleteme2121 at DELETEMEhotmail dot com
08-Mar-2005 07:36
remember that putting an invalid date such as 2005-02-31 through mktime() http://uk2.php.net/manual/en/function.mktime.php you end up with a correct date, the above example would end up as 2005-03-03 (on a non-leap year)
LIX
02-Mar-2005 06: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.
25-Feb-2005 04: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
16-Feb-2005 08: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)
rhondle at hotmail dot com
14-Feb-2005 07:56
In addition to validating a date string with a regular expression, it would be a good idea to test it's validity using PHP's checkdate() function.

http://www.php.net/manual/en/function.checkdate.php
Carrajola
12-Feb-2005 02: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.