preg_replace错误

时间:2011-01-17 11:04:40

标签: php regex preg-replace

我有一个需要在大型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

使括号转义的最佳方法是什么,并且还可以转义可能在正则表达式中使用的任何其他字符。

由于

3 个答案:

答案 0 :(得分:5)

您需要preg_quote

答案 1 :(得分:4)

你必须逃避大括号。您可以使用preg_quote()

执行此操作
$entity = preg_quote($entity, '/');

http://www.php.net/manual/en/function.preg-quote.php

答案 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);
}