user3413506
user3413506

Reputation: 13

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

Upvotes: 1

Views: 2015

Answers (2)

Bryan
Bryan

Reputation: 3494

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.

Upvotes: 0

mario
mario

Reputation: 145482

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.

Upvotes: 5

Related Questions