TunaFFish
TunaFFish

Reputation: 11302

Why don't reg expressions from regexlib.com work in PHP?

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?

Upvotes: 1

Views: 288

Answers (2)

Tim Pietzcker
Tim Pietzcker

Reputation: 336418

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).

Upvotes: 2

too much php
too much php

Reputation: 91058

You need to surround it with / delimiters:

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

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

Upvotes: 3

Related Questions