gr8m8 gr8m8 - 5 months ago 10
PHP Question

Can't understand this regex format (Phone number)

I have to format a phone number according to this regex:

/^\\+([0-9]){1,3}\\.([0-9]\\ ?){6,14}$/

For the life of me, I can't figure out the second half of this. My best efforts have me at

  1. It has to start with a backslash

  2. Then 1-3 digits

  3. Then another backslash followed by any character

  4. 6-14 iterations of
    ([0-9]\\ ?)

  5. End of string

If I'm right so far, I can't figure out the format of #4. Or am I totally wrong?

Let's say I have this phone number: +0018005551212 or 18005551212

How would I form this number? Answer would be great but an explanation would be even better. Thanks!!!


No, in all likelihood, the \\ is an escaped \, needed because there is another interpretive layer in there that will detect escape characters. You often see this in bash (as one example) when using double-quoted strings:

pax> echo '\' | sed 's/\\/x/'
pax> echo '\' | sed "s/\\\\/x/"

pax> echo '\' | sed 's/\/x/'
sed: -e expression #1, char 6: unterminated 's' command
pax> echo '\' | sed "s/\\/x/"
sed: -e expression #1, char 6: unterminated 's' command

With the double-quoted string, bash itself interprets the escapes before sed ever sees them, so you need to double-escape. With the single quotes, bash does not interpret the escapes in the string so they're passed to sed as is.

That's based on the fact that, while international phone numbers can begin with +, I've never seen one with a backslash in it.

So the rules are:

^                   start of string
\\+                 a literal +
([0-9]){1,3}        1-3 digits
\\.                 a literal .
([0-9]\\ ?){6,14}   6-14 digits, each with an optional following apace
$                   end of string