PHP - Search string for unwanted characters

I am making register script and I need to protect string from characters other than a-z, A-Z, 0-9, and _. Is there simple way to e.g. search string for characters that are NOT in my array of allowed characters?


Solution 1:

You could perform a search with a regular expression:

preg_match_all('/[^A-Za-z0-9_]/', $string, $matches);

See preg_match_all for more details.

Basically you are searching for characters, which are not present in the indicated list. The matches are stored in $matches. If the returned array is empty, the string passes, otherwise the array contains the disallowed characters.