如何仅对字符串的未引用部分进行替换? [英] How to do replacement only on unquoted parts of a string?

查看:26
本文介绍了如何仅对字符串的未引用部分进行替换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何才能最好地实现以下目标:

How would I best achieve the following:

我想在 PHP 中查找和替换字符串中的值,除非它们在单引号或双引号中.

I would like to find and replace values in a string in PHP unless they are in single or double quotes.

例如.

$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" '

预先感谢您的帮助.

推荐答案

您可以将字符串拆分为带引号/不带引号的部分,然后仅在不带引号的部分上调用 str_replace.这是一个使用 preg_split 的示例:

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

这篇关于如何仅对字符串的未引用部分进行替换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆