简体   繁体   English

为什么这个正则表达式不起作用?

[英]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.我希望数字只是数字、空格、减号、加号,仅此而已,最好以最少 5 位数字和最多 12 位数字结尾。

What happens when I try it out is that nothing goes through, ie this: "12345" fails.当我尝试它时会发生什么没有通过,即:“12345”失败。

Any help?有什么帮助吗?

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

You forgot to use the delimiters.您忘记使用分隔符。

add delimiter + {minlenght,maxlenght}添加分隔符 + {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?您是在寻找总共 5-12 个字符,还是 5-12 个数字,而其他字符是可选的? If it's digits, you want something like this:如果是数字,你想要这样的东西:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM