maze
maze

Reputation: 137

How to prevent slashes from being stripped using Regex?

I can't figure out how to change my regex below to keep the slashes. I want to make sure it only contains letters, numbers, underscores, dashes AND slashes.

($query is something like e.g. /offer/some-offer-bla-bla-bla)

$query = preg_replace('/[^-a-zA-Z0-9_]/', '', $query);

Thanks

Upvotes: 3

Views: 603

Answers (2)

nonopolarity
nonopolarity

Reputation: 150976

One way is to escape the / character but that can make the regex kind of ugly.

You can use a different delimiter like this: (the following is just to show the use of a different delimiter)

$query = "hello/world/0123";
echo $query;
$query = preg_replace('{/}', '', $query);
echo $query;

Upvotes: 0

codaddict
codaddict

Reputation: 454950

Just include the / in the character class. But since you are using / as the regex delimiter you need to escape it aswell as \/:

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

You can make your regex shorter by using \w in place of [a-zA-Z0-9_], also you can avoid escaping the / by using a different delimiter say ~:

$query = preg_replace('~[^-\w/]~', '', $query);

Upvotes: 6

Related Questions