views:

27

answers:

2

Is there a canonical function/method for escaping a string to be used in a preg_, such that any special PCRE characters will be interpreted as literal. Basically, a know way to ensure that something like

I am a fancy string (well, that guy ... said I was fancy)

is transformed into

I am a fancy string \(well, that guy \.\.\. said I was fancy\)

The use case is something like

$re = get_string_from_somewhere();
$re = our_magic_function($re);
preg_match_all('%'.$re.'%',$string, $matches);
+5  A: 

I believe that preg_quote() is the answer you're looking for...

If you're using a custom delimiter (as you do in your example), be sure to set the second parameter ($delimiter) to the one used in the regex... So your call would be preg_quote($string, '%');

ircmaxell
No idea how i missed that on the php.net site.
Alan Storm
+1  A: 

preg_quote()

Mark Baker