これを行う簡単な方法の 1 つを次に示します。引用符を使用して文字列を分割/展開します。結果の配列の最初の ( 0
-index ) 要素と各偶数番号のインデックスは、引用符で囲まれていないテキストです。奇数は引用符で囲みます。例:
Test "testing 123" Test etc.
^0 ^1 ^2
次に、偶数番目の配列要素のみで魔法の言葉 (toys) を置換 (cards) に置き換えます。
サンプルコード:
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