This function does the trick:
function str_replace_outside_quotes($replace,$with,$string){
$result = "";
$outside = preg_split('/("[^"]*"|\'[^\']*\')/',$string,-1,PREG_SPLIT_DELIM_CAPTURE);
while ($outside)
$result .= str_replace($replace,$with,array_shift($outside)).array_shift($outside);
return $result;
}
. , , , , , .. ( - ). , .
$text = "Many apples are falling from the trees.
\"There another apple over there!\"
'Seedling apples are an example of \"extreme heterozygotes\".'";
$replace = "apples";
$with = "pears";
echo str_replace_outside_quotes($replace,$with,$text);
Many pears are falling from the trees.
"There another apple over there!"
'Seedling apples are an example of "extreme heterozygotes".'