Question

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 quoted string" '

Thanks in advance for your help.

Was it helpful?

Solution

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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top