PHP: Check if special characters from a list are present in a string

做~自己de王妃 提交于 2019-12-24 12:07:32

问题


This is a newbie question.

Let's say I have an array of illegal characters, i.e.:

$special_chars = array("?", "[", "]", "/", "\\", "=", "<", ">", ":", ";", ",", "'", "\"", "&", "$", "#", "*", "(", ")", "|", "~", "`", "!", "{", "}");

I would need to check if any of these characters is present in a string, i.e.

$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.


回答1:


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.

The least effort would be converting your special character list into a regex charclass and testing against the string.




回答2:


If you're just trying to match all non word characters, preg_match_all is probably a better solution. 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.

Now the variable $matches is an array containing all of the non-word characters. 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.



来源:https://stackoverflow.com/questions/22368313/php-check-if-special-characters-from-a-list-are-present-in-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!