preg_replace错误

Liz*_*ard 0 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);
}
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

Warning (2): preg_replace() [function.preg-replace]: Compilation failed: missing ) at offset XX
Run Code Online (Sandbox Code Playgroud)

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

谢谢

Flo*_*ern 5

你必须摆脱大括号。你可以用 来做到这一点preg_quote()

$entity = preg_quote($entity, '/');
Run Code Online (Sandbox Code Playgroud)

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