我正在尝试测试一个字符串,看看它是否包含字母数字或标点符号以外的字符,如果包含,则设置错误。我有下面的代码,但它似乎不起作用,因为它让"CZW205é"通过。我对正则表达式感到绝望,似乎无法解决问题。
if(!preg_match("/^[a-zA-Z0-9's'p{P}]/", $product_id)) {
$errors[$i] = 'Please only enter alpha-numeric characters, dashes, underscores, colons, full-stops, apostrophes, brackets, commas and forward slashes';
continue;
}
提前感谢您的帮助。
你可以做
if(preg_match("/[^a-zA-Z0-9's'p{P}]/", $product_id)) {
$errors[$i] = 'Please only enter alpha-numeric characters, dashes, underscores, colons, full-stops, apostrophes, brackets, commas and forward slashes';
continue;
}
[^...]
是一个否定的字符类,一旦它找到不属于你的类的内容,它就会匹配。
(因此我删除了preg_match()
之前的否定)
/^[a-zA-Z0-9's'p{P}]+$/
不要忘记用$
标记字符串的末尾
发生这种情况是因为您只匹配第一个字符,请尝试以下代码:
if(preg_match("/[^'w's'p{P}]/", $product_id)) {
$errors[$i] = 'Please only enter alpha-numeric characters, dashes, underscores, colons, full-stops, apostrophes, brackets, commas and forward slashes';
continue;
}
注意:'w
是[a-zA-Z0-9_]
的简写