How to do replacement only on unquoted parts of a string?

大兔子大兔子 提交于 2020-01-05 04:30:11

问题


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.


回答1:


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);


来源:https://stackoverflow.com/questions/4209293/how-to-do-replacement-only-on-unquoted-parts-of-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!