1

我将如何最好地实现以下目标:

我想在 PHP 中查找和替换字符串中的值,除非它们是单引号或双引号。

例如。

$string = 'The quoted words I would like to replace unless they are "part of a quoted string" ';

$terms = array(
  'quoted' => 'replaced'
);

$find = array_keys($terms);
$replace = array_values($terms);    
$content = str_replace($find, $replace, $string);

echo $string;

echo'd 字符串应该返回:

'The replaced words I would like to replace unless they are "part of a quoted string" '

在此先感谢您的帮助。

4

1 回答 1

1

您可以将字符串拆分为引用/未引用的部分,然后str_replace仅调用未引用的部分。这是一个使用示例preg_split

$string = 'The quoted words I would like to replace unless they are "part of a quoted string" ';
$parts = preg_split('/("[^"]*"|\'[^\']*\')/', $string, -1, PREG_SPLIT_DELIM_CAPTURE);
for ($i = 0, $n = count($parts); $i < $n; $i += 2) {
    $parts[$i] = str_replace(array_keys($terms), $terms, $parts[$i]);
}
$string = implode('', $parts);
于 2010-11-17T21:25:33.283 回答