- How to remove non-alphanumeric characters from a string
SOLUTION 1:
- To remove non-alphanumeric characters from a string,first you need to basically defined it as a regex.
- For unicode characters, we have to use the below example:
- We can also use the regular expression.
Here is an example:
[pastacode lang=”javascript” manual=”%24str%20%3D%20preg_replace(‘%2F%5B%5Ea-z%5Cd%20%5D%2Fi’%2C%20”%2C%20%24str)%3B%0A” message=”javascript code” highlight=”” provider=”manual”/]we need to note of the following
- The i stands for case insensitive.
- ^ means, does not start with.
- \d matches any digit.
- a-z matches all characters between a and z. Because of the i parameter you don’t have to specify a-z and A-Z.
- After \d there is a space, so spaces are allowed in this regex
- here’s a really simple regex for remove non-alpha numeric characters:
and used as you need it (with a forward / slash delimiter).
[pastacode lang=”javascript” manual=”%20preg_replace(%22%2F%5CW%7C_%2F%22%2C%20”%2C%20%24string)%3B%0A” message=”javascript code” highlight=”” provider=”manual”/] [ad type=”banner”]- Test it here with this great tool that explains what the regex is doing:
- A PHP function that strips a string of all characters other than alphanumeric characters:
- We can also use the below code to Remove All Non-Numeric Characters
- This code will delete any non-alphanumeric characters specified between the brackets, and then output/return the clean version.
The code:
[pastacode lang=”php” manual=”%3C%3Fphp%20%24string%20%3D%20%22Here!%20is%20some%20text%2C%20and%20numbers%2012345%2C%20and%20symbols%20!%C2%A3%24%25%5E%26%22%3B%0A%24new_string%20%3D%20preg_replace(%22%2F%5B%5Ea-zA-Z0-9%5Cs%5D%2F%22%2C%20%22%22%2C%20%24string)%3B%0Aecho%20%24new_string%20%3F%3E%0A” message=”php code” highlight=”” provider=”manual”/]