Function to return only alpha-numeric characters from string?
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) ✓
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)
preg_replace, you could always use PHP's filter functions using the
filter_var() function with
Answer #3 (1 Votes)
- Santize for numbers [0-9] and alphabets in general [\pL]:
$string = preg_replace("/[^0-9\pL]+/", "", $string)
- Santize specifically for the alphabets A to Z (case-insensitive) [a-zA-Z]:
$string = preg_replace("/[^a-zA-Z]+/", "", $string)