How to do replacement only on unquoted parts of a string?
How would I best achieve the following:
I would like to find and replace values in a string in PHP unless they are in single or double quotes.
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
'd string should return:
'The replaced words I would like to replace unless they are "part of a quot开发者_运维知识库ed string" '
Thanks in advance for your help.
You could split the string into quoted/unquoted parts and then call str_replace
only on the unquoted parts. Here’s an example using 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);
精彩评论