首页 > 解决方案 > 正则表达式不匹配标签内的文本

问题描述

我试图<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;

标签: phpregex

解决方案


你正在尝试做的事情,不应该尝试。RegEx 无法解析 HTML。则表达式用于正则语言,HTML 是不规则语言。因此,它根本无法处理您的要求。

为了进一步强调这一点,让我为您指出一个最有力的答案来装饰这个论坛。


推荐阅读