How can I remove all non alphanumeric characters from a string in PHP?
This is the code, that I'm currently using:
$url = preg_replace('/\s+/', '', $string);
It only replaces blank spaces.
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.
A common solution to remove all non-alphanumeric characters from a String is with regular expressions. The idea is to use the regular expression [^A-Za-z0-9] to retain only alphanumeric characters in the string. You can also use [^\w] regular expression, which is equivalent to [^a-zA-Z_0-9] .
You can use preg_replace in this case; $res = preg_replace("/[^0-9]/", "", "Every 6 Months" );
Use the isalnum() Method to Remove All Non-Alphanumeric Characters in Python String. We can use the isalnum() method to check whether a given character or string is alphanumeric or not. We can compare each character individually from a string, and if it is alphanumeric, then we combine it using the join() function.
$url = preg_replace('/[^\da-z]/i', '', $string);
At first take this is how I'd do it
$str = 'qwerty!@#$@#$^@#$Hello%#$'; $outcome = preg_replace("/[^a-zA-Z0-9]/", "", $str); var_dump($outcome); //string(11) "qwertyHello"
Hope this helps!
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