简体   繁体   中英

How to properly escape a string for use in regular expression in PHP?

I am trying to escape a string for use in a regular expression in PHP. So far I tried:

preg_quote(addslashes($string));

I thought I need addslashes in order to properly account for any quotes that are in the string. Then preg_quote escapes the regular expression characters.

However, the problem is that quotes are escaped with backslash, eg \\' . But then preg_quote escapes the backslash with another one, eg \\\\' . So this leaves the quote unescaped once again. Switching the two functions does not work either because that would leave an unescaped backslash which is then interpreted as a special regular expression character.

Is there a function in PHP to accomplish the task? Or how would one do it?

The proper way is to use preg_quote and specify the used pattern delimiter .

preg_quote() takes str and puts a backslash in front of every character that is part of the regular expression syntax... characters are: . \\ + * ? [ ^ ] $ ( ) { } = ! < > | : - . \\ + * ? [ ^ ] $ ( ) { } = ! < > | : -

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

Your regex with modification mentioned in comments by @CasimiretHippolyte and @anubhava.

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

Maybe wanted to use \\b word boundary . No need for any additional escaping.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM