简体   繁体   English

PHP preg_match仅允许数字,空格“ +”和“-”

[英]PHP preg_match to allow only numbers,spaces '+' and '-'

I need to check to see if a variable contains anything OTHER than 0-9 and the "-" and the "+" character and the " "(space). 我需要检查变量是否包含0-9以外的其他内容以及“-”和“ +”字符以及“”(空格)。

The preg_match I have written does not work. 我写的preg_match不起作用。 Any help would be appreciated. 任何帮助,将不胜感激。

<?php

$var="+91 9766554433";

if(preg_match('/[0-9 +\-]/i', $var))
 echo $var;
?>

You have to add a * as a quantifier to the whole character class and add anchors to the start and end of the regex: ^ and $ means to match only lines containing nothing but the inner regex from from start to end of line. 您必须在整个字符类中添加*作为量词,并在正则表达式的开头和结尾添加锚点^$表示从行首到行尾仅匹配除内部正则表达式之外的所有行。 Also, the i modifier is unnecessary since there is no need for case-insensitivity in this regex. 另外, i修饰符也是不必要的,因为在此正则表达式中无需区分大小写。

This should do the work. 这应该做的工作。

if(!preg_match('/^[0-9 +-]*$/', $var)){
     //variable contains char not allowed 
}else{
     //variable only contains allowed chars
}

Just negate the character class: 否定字符类:

if ( preg_match('/[^0-9 +-]/', $var) )
    echo $var;

or add anchors and quantifier: 或添加锚点和量词:

if ( preg_match('/^[0-9 +-]+$/', $var) )
    echo $var;

The case insensitive modifier is not mandatory in your case. 不区分大小写的修饰符在您的情况下不是必需的。

You can try regex101.com to test your regex to match your criteria and then on the left panel, you'll find code generator, which will generate code for PHP, Python, and Javascript. 您可以尝试regex101.com来测试您的正则表达式是否符合您的条件,然后在左侧面板上找到代码生成器,该代码生成器将为PHP,Python和Javascript生成代码。

$re = "/^[\\d\\s\\+\\-]+$/i"; 
$str = "+91 9766554433"; 

preg_match($re, $str, $matches);

You can take a look here . 你可以在这里看看。

Try see if this works. 尝试看看是否可行。 I haven't gotten around to test it beforehand, so I apologize if it doesn't work. 我还没有事先对其进行测试,因此,如果无法正常工作,我深表歉意。

if(!preg_match('/^[0-9]+.-.+." ".*$/', $var)){
     //variable contains char not allowed 
}else{
 //variable only contains allowed chars
}

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

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