如何使用preg_match
查看字符串中是否存在特殊字符[^'£$%^&*()}{@:'#~?><>,;@|\-=-_+-¬`]
?
发布于 2010-10-15 05:10:00
[\W]+
将匹配任何非单词字符。
但要仅匹配问题中的字符,请使用以下命令:
$string="sadw$"
if(preg_match("/[\[^\'£$%^&*()}{@:\'#~?><>,;@\|\\\-=\-_+\-¬\`\]]/", $string)){
//this string contain atleast one of these [^'£$%^&*()}{@:'#~?><>,;@|\-=-_+-¬`] characters
}
发布于 2016-02-04 19:57:37
我的函数让生活变得更简单。
function has_specchar($x,$excludes=array()){
if (is_array($excludes)&&!empty($excludes)) {
foreach ($excludes as $exclude) {
$x=str_replace($exclude,'',$x);
}
}
if (preg_match('/[^a-z0-9 ]+/i',$x)) {
return true;
}
return false;
}
第二个参数($excludes)可以与您希望忽略的值一起传递。
用法
$string = 'testing_123';
if (has_specchar($string)) {
// special characters found
}
$string = 'testing_123';
$excludes = array('_');
if (has_specchar($string,$excludes)) { } // false
发布于 2019-05-29 00:30:15
对我来说,这是最有效的:
$string = 'Test String';
$blacklistChars = '"%\'*;<>?^`{|}~/\\#=&';
$pattern = preg_quote($blacklistChars, '/');
if (preg_match('/[' . $pattern . ']/', $string)) {
// string contains one or more of the characters in var $blacklistChars
}
https://stackoverflow.com/questions/3937569
复制相似问题