Regular expression to delete all characters except a-zA-Z0-9?

Possible duplicate:
Removing non-alphanumeric characters from a string

Can I know how to support only letters az, AZ and numbers 0-9 and delete all characters, including & @ #%, and replace it with '' using strtr and regex in php? Thanks

+4
source share
3 answers
$new_string = preg_replace('~[^a-zA-Z0-9]+~', '', $string); 

[^a-zA-Z0-9] is just a negative character class (ie, matches any character that is not part of the class).

+8
source

As you know, you can remove these characters like this:

 $result = preg_replace("/[a-zA-Z0-9]/", "", $text); 

So, in order to get what you want (save these characters, delete any others), we need to "invert" this:

 $result = preg_replace("/[^a-zA-Z0-9]/", "", $text); 

You can also use \ W to remove something “non-verbal”:

 $result = preg_replace("/\W/", "", $text); 

The word symbol is any letter or number or underscore, that is, any symbol that can be part of the word Perl. The definition of letters and numbers is controlled by the PCRE character tables and may vary if language matching occurs. For example, in "fr" (French), for accented characters, some character codes greater than 128 are used, and they correspond to \ w.

http://www.php.net/manual/en/regexp.reference.escape.php

+6
source

strtr cannot use regex.

 preg_replace('/[^a-zA-Z0-9]/', '', $stringToCheck); 
+1
source

All Articles