tags:

views:

57

answers:

4

How would I strip out all characters from a string that does NOT contain: [a-zA-Z0-9\-\/_] ?

In other words, I'd like to specify what I DO want rather than what I don't. Thanks.

+5  A: 

Easiest way:

preg_replace("/[^a-zA-Z0-9-\/_]/", '', $string);

Another approach would be to do a match and then implode the matched values.

Jakub Hampl
Wouldn't that eliminate a-z, A-Z, 0-9, -, / and _ ? I don't want that. I want to KEEP those without creating a 10kb line of things I don't want.
ShiGon
Exactly, the little `^` hat means *everything else apart from the stuff in here*.
Jakub Hampl
WOW! I mistook that as a beginning-of-string symbol. All these years and I had no idea. Thanks so much.
ShiGon
Well you were sort of right - it is also a beginning of string symbol. Just when used inside square brackets it gets the meaning of **not**.
Jakub Hampl
@pax: Actually, it's the *character-class* NOT operator--and only if it's the first character after the opening `[`.
Alan Moore
+1  A: 

try the following

preg_replace("/[^a-zA-Z0-9-\/_]/", "", $string);
josnidhin
A: 

If you want to keep a "/" and "\"

preg_replace("/[^a-zA-Z0-9-\\\/_]/", '', $string);
Geek Num 88
I'm pretty sure the backslash was only there to escape the forward-slash; now that I've added code formatting to the question, you can see there's one in front of the hyphen as well.
Alan Moore
Yes I can see that now, Thanks
Geek Num 88
A: 

Shortest way to do it:

echo(preg_replace('~[^\w-/]~i', '', 'H#el/-l0:0.'));

Outputs:

"Hel/-l00"
pygorex1