Escaping string for use in regular expression

Tomba picture Tomba · Feb 8, 2011 · Viewed 17.8k times · Source

Possible Duplicate:
Is there a PHP function that can escape regex patterns before they are applied?

I want to use a string stored in a variable in a regular expression. What's the best way (in PHP) to escape a string for use in a (PCRE) regular expression?

For example,

$text = 'm/z';  // this is the text I want to use as part of my regular expression
$text_regexp = '#' . $text . '#i';  // this is my regular expression

Would give

$text_regexp = '#m/z#i';

But I would want the following regular expression:

$text_regexp = '#m\/z#i';

This is a contrived example, but I wanted to illustrate the point simply.

Answer

webbiedave picture webbiedave · Feb 8, 2011

preg_quote

From the manual:

puts a backslash in front of every character that is part of the regular expression syntax

You can also pass the delimiter as the second parameter and it will also be escaped. However, if you're using # as your delimiter, then there's no need to escape /