How to prevent slash using regex?

I cannot figure out how to change my regex below to preserve slashes. I want to make sure that it contains only letters, numbers, underscores, dashes, and slashes.

($ query is something like, for example, / offer / some -offer-bla-bla-bla)

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

thank

+3
source share
2 answers

Just include /in the character class. But since you use it /as a regular expression terminator, you need to get away from it, as well \/:

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

You can make your regular expression shorter by using \winstead [a-zA-Z0-9_], and you can avoid escaping /with another delimiter ~::

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

- /, .

: ( , )

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

Source: https://habr.com/ru/post/1772841/


All Articles