Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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, 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?

like image 600
Daniel Avatar asked Nov 09 '22 02:11

Daniel


1 Answers

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.

like image 133
bobble bubble Avatar answered Nov 14 '22 22:11

bobble bubble