繁体   English   中英

php preg_match或preg_replace来验证

[英]php preg_match or preg_replace to validate

我想检查一个字符串,只允许az AZ 0-9 . / ? & az AZ 0-9 . / ? & az AZ 0-9 . / ? &但我不确定如何使用preg_match()。

如果您还可以解释代码的每个部分,我会很感激! (即为什么要添加/^以及如何添加/

谢谢

这里是:

$input = 'Hello...?World';
$regex = '~^[a-z0-9&./?]+$~i';

if (preg_match($regex, $input)) {
  echo "yeah!";
}

您可以构建自己的角色类并以这种方式验证字符串。

说明:

~
^                        # string start
[                        # start character class 
  a-z                    # letters from a to z
  0-9                    # digits from 0 to 9
  &./?                   # &,.,/ and ? chars
]                        # end character class
+                        # repeat one or more time
$                        # string end
~ix
if ( preg_match('[^a-zA-Z0-9./?&]', 'azAZ09./?&') ) {
     //found a character that does not match!
 } else //regex failed, meaning all characters actually match

非常类似于ioseb,但您需要包含AZ,因为大写与小写不同。 他已经为角色写了很棒的指南,所以我只提出另一种正则表达式。

我依赖于否定(开头的^,当包含在字符类'[]'的开头时,它具有不同的含义),后面跟着“允许的字符”字符串。

这样,如果正则表达式发现任何不是允许的字符([]表示一个字符),它将停止解析并返回true,这意味着找到了无效的字符串。

暂无
暂无

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

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