开发者

Why isn't this regular expression working?

开发者 https://www.devze.com 2023-03-28 02:52 出处:网络
if(!preg_match(\'^[\\+0-9\\s\\-]+$\',$tel_nr)) { die(\"Invalid num开发者_StackOverflowber.\"); } I want the number to be only numbers, spaces, minus sign, plus sign, nothing else, end preferably m
if(!preg_match('^[\+0-9\s\-]+$',$tel_nr))
            { 
                die("Invalid num开发者_StackOverflowber.");
            } 

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?


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

You forgot to use the delimiters.


add delimiter + {minlenght,maxlenght}

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


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.");
}     


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))
0

精彩评论

暂无评论...
验证码 换一张
取 消