[英]PHP: Check if special characters from a list are present in a string
This is a newbie question. 这是一个新手问题。
Let's say I have an array of illegal characters, ie: 假设我有一系列非法字符,即:
$special_chars = array("?", "[", "]", "/", "\\", "=", "<", ">", ":", ";", ",", "'", "\"", "&", "$", "#", "*", "(", ")", "|", "~", "`", "!", "{", "}");
I would need to check if any of these characters is present in a string, ie 我需要检查字符串中是否存在这些字符,即
$my_string = "abcde!fgh"
I have googled for a solution to do this in a simple manner but haven't found any satisfactory answer. 我已经用谷歌搜索了一种简单的方法来解决这个问题,但是没有找到满意的答案。
Any help on this would be much appreciated. 任何帮助,将不胜感激。
A concise way to do it with your two data structures would be: 使用您的两个数据结构的一种简洁方法是:
count( array_intersect( str_split($my_string), $special_chars ) )
That would also tell you how many of the special characters are in the string. 这还将告诉您字符串中有多少个特殊字符。
You could otherwise write a loop for your character list and manually probe with strpos
. 否则,您可以为字符列表编写一个循环,然后手动使用
strpos
探测。
The least effort would be converting your special character list into a regex charclass and testing against the string. 最少的工作就是将您的特殊字符列表转换为regex charclass并针对字符串进行测试。
If you're just trying to match all non word characters, preg_match_all is probably a better solution. 如果您只是想匹配所有非单词字符,那么preg_match_all可能是一个更好的解决方案。 Give it a try.
试试看。
preg_match_all('/[\W]{1}/',$my_string, $matches);
the \\W matches any non-word character and the {1} specified to grab only 1 of them and quit, using preg_match_all instead of preg_match gets all sections that match the regex instead of just the first one. \\ W匹配任何非单词字符,并且指定的{1}仅捕获其中的一个并退出,使用preg_match_all而不是preg_match可以获取与正则表达式匹配的所有部分,而不仅仅是第一个。
Now the variable $matches is an array containing all of the non-word characters. 现在,变量$ matches是一个包含所有非单词字符的数组。 If you want to know how many you can do
如果您想知道您可以做多少
$numSpecialCharacters = preg_match_all('/[\W]{1}/',$my_string);
If you don't care how many, and just want to check if it contains one, you can just use a conditional 如果您不在乎有多少,只想检查它是否包含一个,则可以使用有条件的
if($numSpecialCharacters === false)
//something went wrong.
elseif( $numSpecialCharacters > 0)
//the string contains special characters
You can find the documentations here .Hope that helps. 您可以在此处找到文档。希望对您有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.