This article demonstrates how to remove all non-alphanumeric characters from a string in PHP.

Regular expressions are a simple way to remove non-alphanumeric characters from a string. In PHP, regular expressions are often used to find and replace character patterns in strings with the preg_replace() function. The following solution demonstrates the usage of preg_replace() by removing all characters from the string that do not fall in the ASCII alphanumeric range (a-z, A-Z, and 0-9) and are not a space or an underscore.

Download  Run Code

 
Here, ^ is a negated character class that matches anything that is not enclosed within the square brackets. The range of alphanumeric characters is specified by using a hyphen. a-z matches all lowercase alphabets between a and z, A-Z matches all uppercase alphabets between A and Z, and 0-9 matches all digits between 0 and 9.

 
The pattern can be simplified to '/[^a-z0-9_ ]/i' or '/[^A-Z0-9_ ]/i', where i flag enables case-insensitive search. To remove underscore and space as well, change the pattern to '/[^a-z0-9]/i', as shown below.

Download  Run Code

 
It is also possible to use the character classes \w and \s where \w matches any alphanumeric character, including the underscore, and \s matches any whitespace character, including Unicode spaces. You can say that \w it is same as using [A-Za-z0-9_], and \s is same as [ \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff] regular expression.

Download  Run Code

 
Alternatively, you can use the \W character class, which is the inverse of \w. It is equivalent to [^A-Za-z0-9_] i.e., \W matches any non-word character from the basic Latin alphabet. It should be noted that it strictly removes non-alphanumeric characters from a string, including spaces, but retains the underscore character. If you also need to remove the underscore, consider using the pattern [\W|_].

Download  Run Code

 
Finally, you can use the [[:alnum:]] and [[:space:]] character classes in regular expressions. The alnum character class denotes alphabetic and numeric characters, and it is equivalent to [a-zA-Z0-9]. Similarly, the space character class identifies all whitespace characters like space, tab, form feed, new line (line feed), etc.

The following program demonstrates the usage of character classes for removing all non-alphanumeric and non-whitespace characters from a string. It uses the u flag, which enables the support of Unicode characters. Note that the underscore character is also removed.

Download  Run Code

That’s all about removing all non-alphanumeric characters from a string in PHP.