Reputation: 71
im trying to validate phone number in php. The requirements are (0d)dddddddd or 0d dddddddd where d is 0-9. This is what I have right now
if(!preg_match("/^0[0-9]{9}$/", $phone))
{
//wrong format
}
I have tried several similar questions, but still cant understand regex very well. Can anyone help me fix the regex?
Upvotes: 0
Views: 1285
Reputation: 724
try this
if(!preg_match("^(?:\(0\d\)|0\d\s)\d{8}$", $phone))
{
//wrong format
}
Upvotes: 0
Reputation: 174696
You could try the below code,
if(!preg_match("~^(?:0\d\s|\(0\d\))\d{8}$~", $phone))
{
//wrong format
}
Explanation:
^ the beginning of the string
(?: group, but do not capture:
0 '0'
\d digits (0-9)
\s whitespace
| OR
\( '('
0 '0'
\d digits (0-9)
\) ')'
) end of grouping
\d{8} digits (0-9) (8 times)
$ before an optional \n, and the end of the
string
Upvotes: 1
Reputation: 26667
^((\(0\d\))|(0\d ))\d{8}$
matches
(05)12345678
05 12345678
see the example http://regex101.com/r/zN4jE4/1
if(!preg_match("/^((\(0\d\))|(0\d ))\d{8}$/", $phone))
{
//wrong format
}
Upvotes: 0
Reputation: 67968
^(?:\(0\d\)|0\d\s)\d{8}$
Try this.See demo.
http://regex101.com/r/wQ1oW3/8
Upvotes: 0