preg_match特殊字符

时间:2010-10-14 21:04:58

标签: php

如何使用preg_match查看字符串中是否存在特殊字符[^'£$%^&*()}{@:'#~?><>,;@|\-=-_+-¬`]

7 个答案:

答案 0 :(得分:11)

[\W]+将匹配任何非单词字符。

答案 1 :(得分:10)

使用preg_match。此函数接受正则表达式(模式)和主题字符串,如果匹配则返回1,如果不匹配则返回0,如果发生错误则返回false

$input = 'foo';
$pattern = '/[\'\/~`\!@#\$%\^&\*\(\)_\-\+=\{\}\[\]\|;:"\<\>,\.\?\\\]/';

if (preg_match($pattern, $input)){
    // one or more matches occurred, i.e. a special character exists in $input
}

您还可以为执行正则表达式匹配功能指定标志和偏移量。请参阅上面的文档链接。

答案 2 :(得分:4)

我的功能让生活更轻松。

$string = 'testing_123';
if (has_specchar($string)) { 
    // special characters found
} 

$string = 'testing_123';
$excludes = array('_');
if (has_specchar($string,$excludes)) { } // false

第二个参数($ excludes)可以与您想要忽略的值一起传递。

用法

(?i)

答案 3 :(得分:0)

您可以使用preg_quote来转义字符以在正则表达式中使用:

preg_match('/' . preg_quote("[^'£$%^&*()}{@:'#~?><>,;@|\-=-_+-¬`]", '/') . '/', $string);

http://php.net/manual/en/function.preg-quote.php

答案 4 :(得分:0)

对我来说,这最有效:

$string = 'Test String';

$blacklistChars = '"%\'*;<>?^`{|}~/\\#=&';

$pattern = preg_quote($blacklistChars, '/');
if (preg_match('/[' . $pattern . ']/', $string)) {
   // string contains one or more of the characters in var $blacklistChars
}

答案 5 :(得分:0)

这适用于所有PHP版本。结果是布尔型,需要相应地使用。

要检查ID是否包含字符串,可以使用以下字符:

preg_match( '/[a-zA-Z]/', $string );

要检查字符串是否包含数字,可以使用它。

preg_match( '/\d/', $string );

现在要检查字符串是否包含特殊字符,应使用此字符。

preg_match('/[^a-zA-Z\d]/', $string);

答案 6 :(得分:0)

如果你想匹配特殊字符

preg_match('/[\'\/~`\!@#\$%\^&\*\(\)_\-\+=\{\}\[\]\|;:"\<\>,\.\?\\\]/', $input)
相关问题