user188962
user188962

Reputation:

Why isn't this regular expression working?

if(!preg_match('^[\+0-9\s\-]+$',$tel_nr))
            { 
                die("Invalid number.");
            } 

I want the number to be only numbers, spaces, minus sign, plus sign, nothing else, end preferably minimum of 5 digits and maximum of 12 digits.

What happens when I try it out is that nothing goes through, ie this: "12345" fails.

Any help?

Upvotes: 0

Views: 132

Answers (4)

Alan Moore
Alan Moore

Reputation: 75232

Are you looking for 5-12 characters total, or 5-12 digits, with the other characters being optional? If it's digits, you want something like this:

if (!preg_match('~^(?:[\+\s\-]*[0-9]){5,12}[\+\s\-]*$~', $tel_nr))

Upvotes: 0

Marian Galik
Marian Galik

Reputation: 876

You have to use / to delimit start and end of the expression. Following code works:

if (!preg_match('/^[\+0-9\s\-]+$/',$tel_nr)) { 
  die("Invalid number.");
}     

Upvotes: 0

genesis
genesis

Reputation: 50976

add delimiter + {minlenght,maxlenght}

if(!preg_match('~^[\+0-9\s\-]{5,12}$~',$tel_nr))
            { 
                die("Invalid number.");
            } 

Upvotes: 0

Shef
Shef

Reputation: 45589

!preg_match('/^[\+0-9\s\-]{5,12}$/',$tel_nr))

You forgot to use the delimiters.

Upvotes: 8

Related Questions