Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all non-alphanumeric characters using preg_replace

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.

like image 839
lisovaccaro Avatar asked Jul 04 '12 00:07

lisovaccaro


People also ask

How do you remove non-alphanumeric characters?

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.

How do I remove all non-alphanumeric characters from a string?

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] .

How remove non numeric characters PHP?

You can use preg_replace in this case; $res = preg_replace("/[^0-9]/", "", "Every 6 Months" );

How do you delete a non-alphanumeric character in Python?

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.


2 Answers

$url = preg_replace('/[^\da-z]/i', '', $string); 
like image 190
John Conde Avatar answered Sep 22 '22 01:09

John Conde


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!

like image 35
sevenadrian Avatar answered Sep 22 '22 01:09

sevenadrian