Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent slashes from being stripped using Regex?

Tags:

regex

php

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

like image 331
maze Avatar asked Nov 22 '25 03:11

maze


1 Answers

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);
like image 87
codaddict Avatar answered Nov 23 '25 21:11

codaddict



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!