正则取消匹配特殊字符串里面的关键词?

发布于 2022-09-11 14:41:20 字数 2269 浏览 28 评论 0

<?php

$body = '
<p style="margin:20px auto; font-size:20px;">
每天都有好心情,我真的很开心 Very happy! oh yes 
<img src="https://example.com/test.jpg" title="好心情的图片">
<a href="https://www.google.com" title="happy"></a>

</p>';
$str = htmlspecialchars_decode($body);
    $keywords = [
       0=>['id'=>1,'title'=>'好心情','url'=>'https://www.example.com/goodMood'],
       1=>['id'=>2,'title'=>'开心','url'=>'https://www.example.com/happy'],
       2=>['id'=>3,'title'=>'happy','url'=>'https://www.example.com/happy1'],
    ];

$content = array_reduce($keywords, function ($c, $v) {
   return preg_replace('/(' . $v['title'] . ')/', '<a style="color:red;" href="'. $v['url'] . '">$1</a>', $c);
}, $str);

echo $content;

请问怎么取消匹配img 和a 标签 title 里面的关键字呢?

在线运行:DEMO

现在的结果:

<p style="margin:20px auto; font-size:20px;"> <a style="color:red;" href="https://www.example.com/<a style="color:red;" href="https://www.example.com/happy1">happy</a>">hello</a>,this is a new <a style="color:red;" href="https://www.example.com/goodMood">function</a> ,Very <a style="color:red;" href="https://www.example.com/happy1">happy</a>! oh yes 
<img src="https://example.com/foo.jpg" title="<a style="color:red;" href="https://www.example.com/happy1">happy</a>">
<a href="https://www.google.com" title="<a style="color:red;" href="https://www.example.com/happy1">happy</a>"></a>
</p>

期待的结果:

<p style="margin:20px auto; font-size:20px;"> <a style="color:red;" href="https://www.example.com/<a style="color:red;" href="https://www.example.com/happy1">happy</a>">hello</a>,this is a new <a style="color:red;" href="https://www.example.com/goodMood">function</a> ,Very <a style="color:red;" href="https://www.example.com/happy1">happy</a>! oh yes
<img src="https://example.com/foo.jpg" title="好心情的图片">happy</a>">
<a href="https://www.google.com" title="happy">happy</a>"></a>
</p>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

傲世九天 2022-09-18 14:41:20
$content = array_reduce($keywords, function ($c, $v) {
   return preg_replace('/(>[^<>]*?)(' . $v['title'] . ')([^<>]*?<)/', '$1<a style="color:red;" href="'. $v['url'] . '">$2</a>$3', $c);
}, $str);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文