Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stripping everything but alphanumeric chars from a string in PHP

Tags:

string

regex

php

I'd like a regexp or other string which can replace everything except alphanumeric chars (a-z and 0-9) from a string. All things such as ,@#$(@*810 should be stripped. Any ideas?

Edit: I now need this to strip everything but allow dots, so everything but a-z, 1-9, .. Ideas?

like image 728
Ali Avatar asked May 08 '09 17:05

Ali


People also ask

How do you remove everything except 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 do you remove non-alphanumeric characters?

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.

How remove all special characters from a string in PHP?

Using str_ireplace() Method: The str_ireplace() method is used to remove all the special characters from the given string str by replacing these characters with the white space (” “).

How remove non numeric characters PHP?

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


1 Answers

$string = preg_replace("/[^a-z0-9.]+/i", "", $string); 

Matches one or more characters not a-z 0-9 [case-insensitive], or "." and replaces with ""

like image 116
gnarf Avatar answered Nov 10 '22 01:11

gnarf