<?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>
";
$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;
how do I unmatch the keywords in img and a tag title?
run online: DEMO
current result:
<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>
expected result:
<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>