25

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.

Community
  • 1
  • 1
Tomba
  • 1,735
  • 5
  • 22
  • 38

4 Answers4

46

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 /

webbiedave
  • 48,414
  • 8
  • 88
  • 101
11

You must use the preg_quote function:

preg_quote ( string $str [, string $delimiter = NULL ] )

Example of a $keyword that must match as a whole word:

$pattern = '/\b' . preg_quote($keyword, '/') . '\b/';
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Leroy
  • 151
  • 4
5

Check this. You can use preg_quote();.

Community
  • 1
  • 1
goto-bus-stop
  • 11,655
  • 2
  • 24
  • 31
5

All these answers are correct, only the metachars need to be escaped. Its kind of too bad that php doesen't have a regex operator like preg_match([operator]/$var/) so the delimeters could be the quoting agent. This way delimeter wouldn't have to be quoted in an external $var. (Perl has this with m//,s/// or =~ operators)

The preg_quote is a nice way to do this, unfortunately, sometimes you want to match literal '\char' without it being escaped to '\char' for instance, and escape the rest. Not many choices with preg_quote().

You could literally set up your own php functions that does quoting of metachars (or take off a quote after preg_quote() ).

like a replace all /([{}\[\]()^\$.|*+?\\<>$delim])/ with \\$1 or something. Set the $delim, and/or take out possibly the escape or any other metachars you don't want escaped.

Just my $.02

  • You can use `quotemeta()` function to escape meta characters. https://www.php.net/manual/en/function.quotemeta.php – jawira Jul 27 '23 at 12:16