1

I am trying to write a regex for my code, the regex is used to validate the phone number format, the first two digits should be either 01,04,05,06,07,08,09 followed by a dash (-) and followed by 6 digits only.

I used the following regex: 0[1456789]{1}-[0-9]{6}. I used the following site to make sure my regex is working correctly: RegExr and I'm testing it on the following 01-123456

However, when I run my code, my function returns as if the number is invalid, which is not.

Here is my code:

function validHomePhone () {
    global $home_phone;

    $home_phone_regex = "0[1456789]{1}-[0-9]{6}";
    return preg_match($home_phone_regex, $home_phone);
}

Why am I getting such results?

2
  • 6
    Don't you need a delimiter in your regex? Commented May 10, 2013 at 13:35
  • 2
    I would also like to recommend a simplified version of your regex /0[14-9]-\d{6}/. Commented May 10, 2013 at 13:37

1 Answer 1

7

You need to enclose the expression in a delimiter, like this:

/0[1456789]{1}-[0-9]{6}/

You should also add the beginning- and end-of-string anchors, otherwise your expression will match anything that contains a valid number:

/^0[1456789]{1}-[0-9]{6}$/

And while we 're at it, the {1} quantifier is redundant:

/^0[1456789]-[0-9]{6}$/

Finally, [1456789] can be reduced to [14-9]. Personally I would not do this because IMHO it reduces readability for no real gain, but it's something that might be useful somewhere else.

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

3 Comments

As an aside your function should take a parameter $home_phone, instead of a global $home_phone function validHomePhone($home_phone) and erase the global line.
I tried first with just / at the beginning and at the end, but didn't try with the ^ and $, I though since it worked without them, there wouldn't be a need for them Thanks Jon
@aizen92: Also pay attention to beiller's comment above, he's 200% right.

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.