php - 正则表达式不匹配标签内的文本
问题描述
我试图<a href="{url}" title="{keyword}">keyword</a>
在找到该关键字时在给定文本上创建一个链接标签。但是该关键字不应该已经在<a></a>
标签内,也不应该与 href 和 title 属性匹配。我正在使用 PHP
例如:
*笔记。我的用例文本没有空格
文字=<p>thisiscatfish</p>
关键字= 鲶鱼
预期产出=<p>thisis<a href="#" title="catfish">catfish</a></p>
但是如果
文字=<p>iam<a href="www.catfish.com" title="catfish">catfish</a></p>
关键字= 鱼
预期输出:<p>iam<a href="www.catfish.com" title="catfish">catfish</a></p>
*注意它不应该匹配 href 和 title 属性并替换它。
我尝试过的 https://paiza.io/projects/WYvDVTUMDg0kFOUo6NEHpQ
问题
到目前为止,我的解决方案也匹配和替换了 href 和 title。如何修改我的正则表达式以不匹配 href 和 title 属性?
function replaceText($text, $keyword, $url) {
$pattern = "/(?!>)$keyword(?!<\/a>)/i";
$replaceWith = "<a href='$url' title='$keyword'>$keyword</a>";
$newText = preg_replace($pattern, $replaceWith, $text);
return $newText;
}
$text = '<p>thisiscatfish</p>';
$newText = replaceText($text, 'catfish', 'www.catfish.com');
$newText2 = replaceText($newText, 'fish', 'www.fish.com');
echo $newText2;
解决方案
你正在尝试做的事情,不应该尝试。RegEx 无法解析 HTML。正则表达式用于正则语言,HTML 是不规则语言。因此,它根本无法处理您的要求。
为了进一步强调这一点,让我为您指出一个最有力的答案来装饰这个论坛。
推荐阅读
- c - 用于打印数组中元素位置的C函数不起作用
- python - 我在 python 中的代码因未知原因重复出现
- java - Springboot JAR 文件 500s
- python - sqlite3.OperationalError:没有这样的表:my_boardgames 但它在那里
- bash - 每多个分隔符拆分一个字符串
- react-native - 使用 API 级别 28 反应原生 Android
- matlab - 为什么在 Matlab 中使用 ifft2 时图像会移位
- apache-spark - Spark将写入操作流式传输到couchbase?
- javascript - 为现代原语扩展对象包装器
- whitespace - Apache Tika 奇怪的空白符号