Function to return only alpha-numeric characters from string?

04/19/2020 18:30:02

I'm looking for a php function that will take an input string and return a sanitized version of it by stripping away all special characters leaving only alpha-numeric.

I need a second function that does the same but only returns alphabetic characters A-Z.

Any help much appreciated.

Verified Answer (203 Votes)

03/05/2011 01:58:07

Warning: Note that English is not restricted to just A-Z.

Try this to remove everything except a-z, A-Z and 0-9:

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

If your definition of alphanumeric includes letters in foreign languages and obsolete scripts then you will need to use the Unicode character classes.

Try this to leave only A-Z:

$result = preg_replace("/[^A-Z]+/", "", $s);

The reason for the warning is that words like résumé contains the letter é that won't be matched by this. If you want to match a specific list of letters adjust the regular expression to include those letters. If you want to match all letters, use the appropriate character classes as mentioned in the comments.


Answer #2 (1 Votes)

03/05/2011 02:16:57

Rather than preg_replace, you could always use PHP's filter functions using the filter_var() function with FILTER_SANITIZE_STRING.


Answer #3 (1 Votes)

04/19/2020 10:05:54
  1. Santize for numbers [0-9] and alphabets in general [\pL]:
$string = preg_replace("/[^0-9\pL]+/", "", $string)
  1. Santize specifically for the alphabets A to Z (case-insensitive) [a-zA-Z]:
$string = preg_replace("/[^a-zA-Z]+/", "", $string)
Hack Hex uses Stack Exchance API by the Stack Exchange Inc. to scrape questions/answers under Creative Commons license.