Non-alphanumeric characters can be remove by using preg_replace() function. This function perform regular expression search and replace. The function preg_replace() searches for string specified by pattern and replaces pattern with replacement if found.
Input : !@GeeksforGeeks2018? Output : GeeksforGeeks2018 Input : Geeks For Geeks Output : GeeksForGeeks
int preg_match( $pattern, $replacement_string, $original_string )
Parameter: This function accepts three parameter as mentioned above and described below:
- $pattern: The pattern that is searched in the string. It must be a regular expression.
- $replacement_string: The matched pattern is replaced by the replacement_string.
- $original_string: It is the original string in which searching and replacement is done.
- After the replacement has occurred, the modified string will be returned.
- If no matches are found, the original string remains unchanged.
Method 1: The regular expression ‘/[\W]/’ matches all the non-alphanumeric characters and replace them with ‘ ‘ (empty string).
$str = preg_replace( '/[\W]/', '', $str);
In the regular expression W is a meta-character that is preceded by a backslash (\W) that acts to give the combination a special meaning. It means a combination of non-alphanumeric characters.
Method 2: The regular expression ‘/[^a-z0-9 ]/i’ matches all the non-alphanumeric characters and replace them with ‘ ‘ (null string).
$str = preg_replace( '/[^a-z0-9 ]/i', '', $str);
In the regular expression:
- i: It is used for case insensitive.
- a-z: It is used for all lowercase letters, don’t need to specify A-Z because of i (case insensitive) already mentioned in the statement.
- 0-9: It is used to match all digits.
- How to remove control characters from PHP string ?
- How to remove all non-printable characters in a string in PHP?
- PHP Ds\Set remove() Function
- Remove a cookie using PHP
- PHP | Ds\Map remove() Function
- D3.js | d3.map.remove() Function
- p5.js | remove() Function
- How to remove SVG content?
- D3.js | d3.set.remove() function
- How to remove underline from a:before using CSS ?
- PHP | Different characters in the given string
- How to get the last n characters of a PHP string?
- How to remove the first character of string in PHP?
- Lodash | _.remove() Method
- Remove new lines from string in PHP
- How to remove a key and its value from an associative array in PHP ?
- Remove border from IFrame using CSS
- How to Remove URL from Printing the Page ?
- PHP | Ds\Vector remove() Function
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.