Why does this regex not work in PHP?

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
KindredHyperion
Forum Newbie
Posts: 2
Joined: Wed Jul 19, 2006 11:52 am

Why does this regex not work in PHP?

Post by KindredHyperion »

Can someone tell me why the following regular expression doesn't work with
PHP, although it does work with almost every single other regex validator
I've found on the internet, including
http://www.sweeting.org/mark/html/revalid.php and
http://www.koralsoft.com/regextester/ ...??

(\+\d{1,3} ?)?(\(\d{1,5}\)|\d{1,5}) ?\d{3} ?\d{0,7}

The code I'm using is:

Code: Select all

<?php
if (ereg('(\+\d{1,3} ?)?(\(\d{1,5}\)|\d{1,5}) ?\d{3} ?\d{0,7}','020 1234
5678'))
    echo "match";
else
    echo "no match";
?>
Which, as far as I can see, should work on the supplied dummy phone number.
For some reason it doesn't though, which may just be a problem with my
coding - bear in mind I haven't written anything in PHP for several years so
I'm a bit rusty.

Thanks!

Adam
User avatar
sweatje
Forum Contributor
Posts: 277
Joined: Wed Jun 29, 2005 10:04 pm
Location: Iowa, USA

Post by sweatje »

Code: Select all

php -r "var_dump(preg_match('~(\+\d{1,3} ?)?(\(\d{1,5}\)|\d{1,5}) ?\d{3} ?\d{0,7}~','020 1234 5678'));"

int(1)
KindredHyperion
Forum Newbie
Posts: 2
Joined: Wed Jul 19, 2006 11:52 am

Post by KindredHyperion »

Aha! I forgot the tildes. There we go!

Thanks for your help!
Post Reply