How do I strip all characters from a string, besides a-z
(with uppercase) and the underscore _
?
Asked
Active
Viewed 1,966 times
0

ellabeauty
- 2,529
- 3
- 21
- 25
-
possible duplicate of [Removing spaces and anything that is not alphanumeric](http://stackoverflow.com/questions/4210419/removing-spaces-and-anything-that-is-not-alphanumeric) – Niet the Dark Absol Mar 28 '12 at 11:16
3 Answers
8
How about a regular expression?
$output = preg_replace('#[^a-zA-Z_]#', '', $input);
This replaces everything that matches the expression with an empty string.
[] is a group of symbols, the ^ at the beginning of the group means: this group contains every character that is NOT mentioned afterwards. So it contains everything that is not a-z or A-Z or the underscore.

Niko
- 26,516
- 9
- 93
- 110
1
Read more about regular expressions. Try this
$string = preg_replace('/[^a-z_]/', '', $string);

safarov
- 7,793
- 2
- 36
- 52
1
You can use the preg_replace
function for this:
$string = 'Text& with* ch@racters that get# removed, but_not_underscore.';
echo preg_replace( '/[^A-Za-z_]/', '', $string );

Tom
- 734
- 2
- 7
- 27