Page 1 of 1

Help replacing ereg with preg_match - SOLVED

Posted: Sun May 27, 2012 1:53 pm
by The Phoenix
I have some old code that has this:

Code: Select all

if (!ereg ("([0-9]{4})/([0-9]{1,2})/([0-9]{1,2})", $startdate, $regs) || $startdate == '')
And of course it is now deprecated.

I tried simply replacing ereg with preg_match, but that didn't work. I suspect I need to escape the / character (it gives "Unknown modifier: '/'"), but I couldn't figure out how.

Re: Help replacing ereg with preg_match

Posted: Sun May 27, 2012 2:05 pm
by The Phoenix
Figured it out. My solution:

Code: Select all

if (!preg_match("/([0-9]{4})\/.([0-9]{1,2})\/.([0-9]{1,2})*/", $startdate, $regs) || $startdate == '')
Used / at start and */ at end, and then escaped the slash with \/.

Re: Help replacing ereg with preg_match

Posted: Sun May 27, 2012 7:03 pm
by requinix
You did more than just convert it to a PCRE expression. You've changed its meaning.

- To escape a character all you do is add a backslash. Periods mean "any character" and you've added two of them.
- If the starting delimiter is "/" then the ending delimiter is also a "/". An asterisk means "any amount of the previous thing" and you've added one of them to the last number set.
To demonstrate what I mean, try validating

Code: Select all

$startdate = "This string contains 9999/ 99/+987654321 which is clearly not a date";
which also shows a separate issue...

Re: Help replacing ereg with preg_match

Posted: Sun May 27, 2012 10:54 pm
by The Phoenix
Ok, so do you have a suggestion on how to fix it correctly?

Based on your feedback, I thought

Code: Select all

if (!preg_match("/([0-9]{4})\/([0-9]{1,2})\/([0-9]{1,2})/", $startdate, $regs) || $startdate == '')
would be successful, but it seems to not be. Regex is not my strong suit. Further suggestions welcome.

Re: Help replacing ereg with preg_match

Posted: Sun May 27, 2012 11:39 pm
by requinix
Two parts. First is an expression:

Code: Select all

$validformat = preg_match('/^(\d\d\d\d)\/(\d\d?)\/(\d\d?)$/', $startdate, $regs);
That only validates the format of the string. Next comes the actual date validation:

Code: Select all

if ($validformat && $regs[1] >= 1900 && $regs[1] <= date("Y") + 1000 && checkdate($regs[2], $regs[3], $regs[1])) {
    // valid
The check with $regs[1] is to make sure it's a reasonable year.

Re: Help replacing ereg with preg_match - SOLVED

Posted: Mon May 28, 2012 9:55 am
by The Phoenix
This was super helpful. Thanks!