正则取消匹配特殊字符串里面的关键词?
<?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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)