user1097772
user1097772

Reputation: 3539

preg_match() + 0-1x and digit

I trying to make regexp for telephone numbers. Resp. for this input:

+420123456 -> valid
123456 -> valid

Respective I want regexp where can be one or zero + folowed 1 or n digits

function isTelephoneNumber($telephone) {
    preg_match("~^[+]{0,1}[0-9]+$~", $telephone,$match);
    return (count($match)>0) ? true:false;
}

also tried

"~^\+{0,1}[0-9]+$~"
"~^[+]?[0-9]+$~"
"~^\+?[0-9]+$~"

But something is wrong with the + character.

Upvotes: 0

Views: 106

Answers (1)

FrancoisBaveye
FrancoisBaveye

Reputation: 1902

Your + is not escaped. This one should do the job :

preg_match("/^\+?\d+$/", $telephone,$match);

\+? => zero or one +

\d+ => one or more digits

Upvotes: 1

Related Questions