How to avoid string for regex use in PHP?

I am trying to avoid a string for use in regex in PHP. So far I have tried:

preg_quote(addslashes($string)); 

I thought that I needed addslashes to correctly consider any quotes that are in the string. Then preg_quote characters.

However, the problem is that the quotes are escaped with a backslash, for example. \' . But then preg_quote removes the backslash from another, for example. \\' . Thus, this once again returns the quote. Switching two functions does not work either because it would leave an unprocessed backslash, which is then interpreted as a special regular expression character.

Is there a function in PHP to complete a task? Or how to do it?

+5
source share
1 answer

The correct way is to use preg_quote and specify the pattern separator to use.

preg_quote () takes str and places a backslash before each character that is part of the regular expression syntax ...: . \ + * ? [ ^ ] $ ( ) { } = ! < > | : - . \ + * ? [ ^ ] $ ( ) { } = ! < > | : -

Trying to use a backslash as a delimiter is a bad idea. Usually you choose a character that is not used in the template. Commonly used slash is /pattern/ , tilde ~pattern~ , number sign #pattern# or percent sign %pattern% . It is also possible to use parenthesized delimiters: (pattern)

Your modified regular expression mentioned in the comments of @CasimiretHippolyte and @anubhava.

 $pattern = '/(?<![az])' . preg_quote($string, "/") . '/i'; 

You might need to use the \b word boundary . No additional screens are needed.

0
source

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


All Articles