php preg_match 特殊字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3937569/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
preg_match special characters
提问by stefanosn
How can I use preg_match
to see if special characters [^'£$%^&*()}{@:'#~?><>,;@|\-=-_+-?`]
exist in a string?
如何使用preg_match
查看[^'£$%^&*()}{@:'#~?><>,;@|\-=-_+-?`]
字符串中是否存在特殊字符?
采纳答案by Trigger Eugene
[\W]+
will match any non-word character.
[\W]+
将匹配任何非单词字符。
回答by pmm
Use preg_match. This function takes in a regular expression (pattern) and the subject string and returns 1
if match occurred, 0
if no match, or false
if an error occurred.
使用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
}
You may also specify flags and offset for the Perform a Regular Expression Matchfunction. See the documentation link above.
您还可以为执行正则表达式匹配函数指定标志和偏移量。请参阅上面的文档链接。
回答by David D
My function makes life easier.
我的功能让生活更轻松。
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;
}
The second parameter ($excludes) may be passed with values you wish to ignore.
第二个参数 ($excludes) 可以与您希望忽略的值一起传递。
Usage
用法
$string = 'testing_123';
if (has_specchar($string)) {
// special characters found
}
$string = 'testing_123';
$excludes = array('_');
if (has_specchar($string,$excludes)) { } // false
回答by Petah
You can use preg_quote
to escape charaters to use inside a regex expression:
您可以使用preg_quote
转义字符以在正则表达式中使用:
preg_match('/' . preg_quote("[^'£$%^&*()}{@:'#~?><>,;@|\-=-_+-?`]", '/') . '/', $string);
回答by codiga
For me, this works best:
对我来说,这最有效:
$string = 'Test String';
$blacklistChars = '"%\'*;<>?^`{|}~/\#=&';
$pattern = preg_quote($blacklistChars, '/');
if (preg_match('/[' . $pattern . ']/', $string)) {
// string contains one or more of the characters in var $blacklistChars
}
回答by Amit kumar jha
This works well for all PHP versions. The resultant is a bool and needs to be used accordingly.
这适用于所有 PHP 版本。结果是一个布尔值,需要相应地使用。
To check id the string contains characters you can use this:
要检查 id 字符串包含的字符,您可以使用:
preg_match( '/[a-zA-Z]/', $string );
preg_match( '/[a-zA-Z]/', $string );
To check if a string contains numbers you can use this.
要检查字符串是否包含数字,您可以使用它。
preg_match( '/\d/', $string );
preg_match( '/\d/', $string );
Now to check if a string contains special characters, this one should be used.
现在要检查字符串是否包含特殊字符,应该使用这个。
preg_match('/[^a-zA-Z\d]/', $string);
preg_match('/[^a-zA-Z\d]/', $string);