Escaping a String for Use in a preg_ Regular Expression
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, $m开发者_开发百科atches);
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, '%');
精彩评论