开发者

Escaping a String for Use in a preg_ Regular Expression

开发者 https://www.devze.com 2023-01-02 14:02 出处:网络
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 li

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, '%');

0

精彩评论

暂无评论...
验证码 换一张
取 消