php - 替换字符串中的文本排除锚文本
问题描述
我想在字符串中搜索单词并想替换该字符串中的第一个出现。我也想排除仅在标签之间的文本。这意味着不应替换具有超链接的文本。
这应该检查新行中的新行。
例子:
这里是 <a> 我的</a> 字符串。我想替换我的字符串。在这个字符串中,只有 1 my 将被替换,它是第一个并且没有锚链接。
将我的替换为“这个”
输出。
这里是 <a> 我的</a> 字符串。我想替换这个字符串。在这个字符串中,只有 1 my 将被替换,它是第一个并且没有锚链接。
谢谢
解决方案
您可以使用此正则表达式匹配第一次出现的“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.
推荐阅读
- python - 在 Conda 环境中安装 Apache-Airflow
- ruby-on-rails - Ruby on Rails active_record:当孩子被保存时,发生父选择查询。为什么以及如何避免这种情况?
- sql-server - 从 Dynamics 365 数据库中的 FetchXml 列中提取实体名称
- c# - 从第二次或更多次调用时如何重置增量变量
- python - 如何检查熊猫数据框列中的年份是否为闰年 - Python
- c++ - 在另一个 VS 项目中引用函数模板的显式实例时出现 LNK2019 错误
- javascript - 我们可以将 onload 函数中声明的数组值用于其他函数吗?
- javascript - 记录按钮不隐藏但不能点击,xrm工作台
- python - 是否可以使用 matplotlib 生成图中所示的图?
- sql-server - 具有现有 ID 号的 SQL Server Employee 表