0

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?

3
  • can you provide some examples of valid numbers Commented Oct 19, 2014 at 7:34
  • Sure. Something like (05)12345678 or 05 12345678 Commented Oct 19, 2014 at 7:41
  • 1
    "Something like" is not good enough when talking about regular expressions. You have to be as exact as you possibly can be. Commented Oct 19, 2014 at 7:54

4 Answers 4

1

You could try the below code,

if(!preg_match("~^(?:0\d\s|\(0\d\))\d{8}$~", $phone))
{
//wrong format
}

DEMO

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the explanation, really helps someone who is still learning like me. Appreciate it.
0
^(?:\(0\d\)|0\d\s)\d{8}$

Try this.See demo.

http://regex101.com/r/wQ1oW3/8

Comments

0
^((\(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
}

Comments

0

try this

if(!preg_match("^(?:\(0\d\)|0\d\s)\d{8}$", $phone))
{
//wrong format
}

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.