如何仅对字符串中未加引号的部分进行替换?

发布于 2024-10-03 05:11:01 字数 547 浏览 5 评论 0原文

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

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

例如。

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

提前感谢您的帮助。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

⒈起吃苦の倖褔 2024-10-10 05:11:01

您可以将字符串拆分为带引号/不带引号的部分,然后仅对不带引号的部分调用 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);

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);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文