如何仅对字符串的非引用部分进行替换?

时间:2010-11-17 21:21:16

标签: php preg-replace str-replace

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

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

EG。

$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'字符串应返回:

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

提前感谢您的帮助。

1 个答案:

答案 0 :(得分: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);