Reputation: 113
I think I've been staring at php too long, I cannot for the life of me figure out why this doesn't work.
I'm trying to match phone numbers with this format (555.555.5555).
if (preg_match("[0-9]{3}.[0-9]{3}.[0-9]{4}", "555.555.5555", $matches)){
echo matches[0];
}
My first thought is I wonder if the . need escaped first or I am just missing something incredibly simple
Upvotes: 1
Views: 66
Reputation: 5705
You need a delimiter for the regex, like e.g. /
or #
. A delimiter is used to separate the regex from possible modifiers.
if (preg_match("/[0-9]{3}\.[0-9]{3}\.[0-9]{4}/", "555.555.5555", $matches)){
echo matches[0];
}
I also changed the dots to \.
since .
is every character (besides a new line, thanks to @Amal Murali in the comments), \.
is only a dot.
Upvotes: 2
Reputation: 76656
If not escaped, the dot character (.
) matches any character (except a new line). If you want to match a literal .
character, you need to escape it with backslash - so you'll need to write \.
You also need to wrap it in valid delimiters, like /
. A delimiter can be any non-alphanumeric, non-backslash, non-whitespace character. ~
, #
, /
etc are some of the most commonly used delimiters. I'm using a forward slash here:
if (preg_match("/[0-9]{3}\.[0-9]{3}\.[0-9]{4}/", "555.555.5555", $matches)){
echo $matches[0];
}
Output:
555.555.5555
Upvotes: 1