hakuna matata
hakuna matata

Reputation: 3327

Regular Expression PHP not validating correctly

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?

Upvotes: 1

Views: 89

Answers (1)

Jon
Jon

Reputation: 437386

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.

Upvotes: 7

Related Questions