<?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>
1 回答
慕桂英4014372
TA贡献1871条经验 获得超13个赞
$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);
- 1 回答
- 0 关注
- 401 浏览
添加回答
举报
0/150
提交
取消