正则表达式来匹配标点符号和字母数字字符

问题描述:

我想测试一个字符串,看看它是否包含除字母数字或标点符号以外的字符,如果是,请设置错误。我有下面的代码,但它似乎没有工作,因为它让“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()前的否定)

+0

非常感谢。对不起,花了这么长时间来回复,但我仍然得到错误500s,所以我测试了什么是错的,我完全相信你的方法正在工作。并感谢所有其他解决方案提供商! – PaulSkinner 2012-08-08 11:48:15

/^[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_]

+0

'\ w'还包括'\ D'和下划线'_' – Toto 2012-08-08 11:55:13

+0

是感谢我忘了:) – Oussama 2012-08-08 11:59:35