这是一种简单的方法。使用引号拆分/分解您的字符串。结果数组中的第一个 ( 0
-index) 元素和每个偶数索引是不带引号的文本;奇数在引号内。例子:
Test "testing 123" Test etc.
^0 ^1 ^2
然后,仅在偶数数组元素中将魔术词(玩具)替换为替换(卡片)。
示例代码:
function replace_not_quoted($needle, $replace, $haystack) {
$arydata = explode('"', $haystack);
$count = count($arydata);
for($s = 0; $s < $count; $s+=2) {
$arydata[$s] = preg_replace('~'.preg_quote($needle, '~').'~', $replace, $arydata[$s]);
}
return implode($arydata, '"');
}
$data = 'tony is playing with toys.
tony is playing with toys... "those toys that are not his" but they are "nice toys," those toys';
echo replace_not_quoted('toys', 'cards', $data);
所以,这里的样本数据是:
tony is playing with toys.
tony is playing with toys... "those toys that are not his" but they are "nice toys," those toys
该算法按预期工作并产生:
tony is playing with cards.
tony is playing with cards... "those toys that are not his" but they are "nice toys," those cards