首页 > 解决方案 > 替换字符串中的文本排除锚文本

问题描述

我想在字符串中搜索单词并想替换该字符串中的第一个出现。我也想排除仅在标签之间的文本。这意味着不应替换具有超链接的文本。

这应该检查新行中的新行。

例子:

这里是 <a> 我的</a> 字符串。我想替换我的字符串。在这个字符串中,只有 1 my 将被替换,它是第一个并且没有锚链接。

将我的替换为“这个”

输出。

这里是 <a> 我的</a> 字符串。我想替换这个字符串。在这个字符串中,只有 1 my 将被替换,它是第一个并且没有锚链接。

谢谢

标签: phpregexstringreplace

解决方案


您可以使用此正则表达式匹配第一次出现的“my”,它不包含在<a> </a>标签中。

^.*?\Kmy(?![^>]*\/\s*a\s*>)

并根据您的帖子将其替换为“this”。

解释:

  • ^--> 输入开始
  • .*?--> 以非贪婪的方式匹配任何字符(捕获我的第一次出现)
  • \K--> 重置任何匹配的东西,所以只有“我的”得到匹配,需要用“这个”替换
  • (?![^>]*\/\s*a\s*>)--> 否定前瞻,以确保<a> </a>标签中不包含“我的”文本。

演示

这是相同的示例 PHP 代码,

$str = 'Here is < a > my < / a > String. I Would like to replace my string. In this string only 1 my will be replace which is first and doesn\'t has anchor link.';
$res = preg_replace('/^.*?\Kmy(?![^>]*\/\s*a\s*>)/','this',$str);
echo $res;

这会像您期望的那样给出以下输出,

Here is < a > my < / a > String. I Would like to replace this string. In this string only 1 my will be replace which is first and doesn't has anchor link.

推荐阅读