如何仅对字符串中未加引号的部分进行替换?
我如何最好地实现以下目标:
我想在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以将字符串拆分为带引号/不带引号的部分,然后仅对不带引号的部分调用
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 usingpreg_split
: