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

<?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>
波斯汪
浏览 402回答 1
1回答

慕桂英4014372

$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);
打开App,查看更多内容
随时随地看视频慕课网APP