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, e.g. \'
. But then preg_quote
escapes the backslash with another one, e.g. \\'
. 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With