1

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

0

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

5 Comments

I had seen that in a few examples and wondered if that was my issue. It didn't show up in all the examples, so what is the purpose of the / and why would I need it?
It tells the parser, where the regex starts and ends. You can add some modifiers after the closing delimiter, like described on php.net/manual/en/reference.pcre.pattern.modifiers.php
Thanks a lot, simple enough.
Small nitpick: . matches every character EXCEPT a new line.
Thanks @AmalMurali, I added it to my answer
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.