user336063
user336063

Reputation:

PHP RegEx specify characters that I DO want?

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.

Upvotes: 2

Views: 92

Answers (4)

leepowers
leepowers

Reputation: 38318

Shortest way to do it:

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

Outputs:

"Hel/-l00"

Upvotes: 0

Geek Num 88
Geek Num 88

Reputation: 5312

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

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

Upvotes: 0

Josnidhin
Josnidhin

Reputation: 12504

try the following

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

Upvotes: 1

Jakub Hampl
Jakub Hampl

Reputation: 40573

Easiest way:

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

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

Upvotes: 5

Related Questions