我有一个需要在大型sting中替换的实体数组,但只有第一次出现(这就是我使用preg_replace
而不是str_replace
的原因),例如:
$entities = array();
$entities[0] = 'string1';
$entities[1] = 'string2';
$entities[2] = 'string2';
$entities[3] = 'Error String ('; ## this is the one that errors because of the bracket
$entities[4] = 'string4';
$entities[5] = 'string5';
foreach ($entities as $entity) {
$new_article = preg_replace('/' . $entity . '/', '##' . $key, $new_article, 1);
}
我收到以下错误:
Warning (2): preg_replace() [function.preg-replace]: Compilation failed: missing ) at offset XX
使括号转义的最佳方法是什么,并且还可以转义可能在正则表达式中使用的任何其他字符。
由于
答案 0 :(得分:5)
您需要preg_quote
答案 1 :(得分:4)
你必须逃避大括号。您可以使用preg_quote()
。
$entity = preg_quote($entity, '/');
答案 2 :(得分:3)
您可以使用preg_quote
$entities = array();
$entities[0] = 'string1';
$entities[1] = 'string2';
$entities[2] = 'string2';
$entities[3] = 'Error String ('; ## this is the one that errors because of the bracket
$entities[4] = 'string4';
$entities[5] = 'string5';
foreach ($entities as $entity) {
$new_article = preg_replace('/' . preg_quote($entity) . '/', '##' . $key, $new_article, 1);
}