RegEx to clear a string

This RegEx is designed to clear user input from a search form.

$query = preg_replace("/[^A-Za-z0-9 _.,*&-]/", ' ', $query);

I also need to add a slash as a valid character, but if I add it, I get an error. I guess I should run away from him, but I can’t find how to do it.

$query = preg_replace("/[^A-Za-z0-9 _.,*&-/]/", ' ', $query); // doesn't works
$query = preg_replace("/[^A-Za-z0-9 _.,*&-//]/", ' ', $query); // doesn't works
$query = preg_replace("/[^A-Za-z0-9 _.,*&-\/]/", ' ', $query); // doesn't works

Using php

+3
source share
4 answers

You can use something else as a separator, and then /try something like this:

$query = preg_replace("%[^A-Za-z0-9 _.,*&-/]%", ' ', $query);

Kobe has also posted the correct way to escape in this situation, but I believe that the regular expression remains more readable when I switch the delimiter to something that I don't use in the expression when possible.

http://www.php.net/manual/en/regexp.reference.delimiters.php ( :)

" PCRE , . - -.

+4

- "\/", "\\/":

$query = preg_replace("/[^A-Za-z0-9 _.,*&\\/-]/", ' ', $query); 

, , - . .

+4
$query = preg_replace("/[^A-Za-z0-9 _.,*&-\/]/", ' ', $query);

, , :

$query = preg_replace('/[^A-Za-z0-9 _.,*&\/-]/', ' ', $query);

, , ", \n,\r\t .. $vars. : escaping/make PHP " / ", " n ", .

, ', .

+2
source

To avoid a character, simply put a backslash in front of it; but don't forget that you are using a double-quoted string, which is probably the reason that makes this harder: you probably have to hide the backslash.


Another solution that I usually use is to work with another regex separator that you don't have in your regex. For example, using #:

$query = preg_replace("#[^A-Za-z0-9 _.,*&-/]#", ' ', $query);

This should solve the problem :-)

+1
source

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


All Articles