Php 如何仅在字符串的无引号部分进行替换?

Php 如何仅在字符串的无引号部分进行替换?,php,preg-replace,str-replace,Php,Preg Replace,Str Replace,我如何才能最好地实现以下目标: 我想在PHP中查找并替换字符串中的值,除非它们是单引号或双引号 例如 echo'd字符串应返回: 'The replaced words I would like to replace unless they are "part of a quoted string" ' 提前感谢您的帮助。您可以将字符串拆分为带引号/不带引号的部分,然后仅对不带引号的部分调用str\u replace。下面是一个示例,使用: $string='我要替换的引用词,除非它们是“引用

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

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

例如

echo
'd字符串应返回:

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

提前感谢您的帮助。

您可以将字符串拆分为带引号/不带引号的部分,然后仅对不带引号的部分调用
str\u replace
。下面是一个示例,使用:

$string='我要替换的引用词,除非它们是“引用字符串的一部分”;
$parts=preg\u split('/(“[^”]*“\'[^\']*\')/”,$string,-1,preg\u split\u DELIM\u CAPTURE);
对于($i=0,$n=count($parts);$i<$n;$i+=2){
$parts[$i]=str_replace(数组_键($terms),$terms,$parts[$i]);
}
$string=内爆(“”,$parts);

您可以将字符串拆分为带引号/不带引号的部分,然后仅对不带引号的部分调用
str\u replace
。下面是使用以下命令的示例:

$string='我要替换的引用词,除非它们是“引用字符串的一部分”;
$parts=preg\u split('/(“[^”]*“\'[^\']*\')/”,$string,-1,preg\u split\u DELIM\u CAPTURE);
对于($i=0,$n=count($parts);$i<$n;$i+=2){
$parts[$i]=str_replace(数组_键($terms),$terms,$parts[$i]);
}
$string=内爆(“”,$parts);
'The replaced words I would like to replace unless they are "part of a quoted string" '
$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);