Как сделать замену только на не заключенных в кавычки частях строки? - PullRequest
1 голос
/ 18 ноября 2010

Как мне лучше всего добиться следующего:

Я бы хотел найти и заменить значения в строке в PHP, если они не заключены в одинарные или двойные кавычки.

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 строка должна возвращать:

'The replaced words I would like to replace unless they are "part of a quoted string" '

Заранее спасибо за помощь.

1 Ответ

1 голос
/ 18 ноября 2010

Вы можете разбить строку на части в кавычках / без кавычек, а затем вызывать str_replace только для частей без кавычек.Вот пример использования 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);
...