I need to remove all characters from a string which aren't in a-z A-Z 0-9
set or are not spaces.
Does anyone have a function to do this?
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.
Using Regular Expression We can use the regular expression [^a-zA-Z0-9] to identify non-alphanumeric characters in a string. Replace the regular expression [^a-zA-Z0-9] with [^a-zA-Z0-9 _] to allow spaces and underscore character.
To remove all non-alphanumeric characters from a string, call the replace() method, passing it a regular expression that matches all non-alphanumeric characters as the first parameter and an empty string as the second. The replace method returns a new string with all matches replaced.
Sounds like you almost knew what you wanted to do already, you basically defined it as a regex.
preg_replace("/[^A-Za-z0-9 ]/", '', $string);
For unicode characters, it is :
preg_replace("/[^[:alnum:][:space:]]/u", '', $string);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With