tags:

views:

55

answers:

2

I found a regex on http://regexlib.com/REDetails.aspx?regexp_id=73
It's for matching a telephone number with international code like so:

^(\(?\+?[0-9]*\)?)?[0-9_\- \(\)]*$

When using with PHP's preg_match, the expression fails? Why is that?

+2  A: 

Because preg_match expects the regex to be delimited, usually with slashes (but, as correctly noted below, other characters are possible as long as they are matched):

preg_match('/^(\(?\+?[0-9]*\)?)?[0-9_ ()-]*$/', $subject)

Apart from that, the original regex was copied wrong - several characters were unescaped. The original on regexlib has a few warts, too (some characters were escaped needlessly).

Tim Pietzcker
The regex can be delimited with things other than slashes. You just have to make sure you match 'em and escape them if they appear in the regex. Unfortunately, I can't find the reference in the manual.
George Marian
yeah I copied it from there, but the backslashes didn't make it, thanks. What characters where escaped needlessly??
FFish
The parentheses and the dash inside the character class - if you put the dash at the start or the end of the class, it doesn't have to be escaped; the parentheses don't have to be escaped at all.
Tim Pietzcker
+3  A: 

You need to surround it with / delimiters:

preg_match('/^(\(?\+?[0-9]*\)?)?[0-9_\- \(\)]*$/', $phoneNumber)

And make sure you don't leave out the backslashes (\).

too much php
Actually you can use any delimiter, you only need to match the starting delimiter with the ending one. I use things like '@', or '!' as delimiters all the time.
quantumSoup
+1, did not know that Aircule
Mailslut