Papayu
Papayu

Reputation: 23

preg_match character class replacing too much

I have a little problem with regex. I want to clean up a string.

Currently I'm using the following regex:

preg_replace("/[^a-zA-Z0-9 _-]/", "", "Example1:2@32");

which gives me: "Example1232"

But the colon shouldn't be replaced, too. I tried it already with:

preg_replace("/[^a-zA-Z0-9 _-:]/", "", "Example1:2@32");

but that doesn't work. Can somebody help me?

Upvotes: 2

Views: 297

Answers (2)

Nazariy
Nazariy

Reputation: 6088

You have to escape - character

preg_replace("/[^a-zA-Z0-9 _\-:]/", "", "Example1:2@32"));

Upvotes: 3

miku
miku

Reputation: 188064

Either method should work:

  • escape the dash - or
  • put the dash - at the end of your regex, since inbetween two other characters it has a certain meaning (namely a range, as in a-z).

Upvotes: 2

Related Questions