Reputation: 137
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
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
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