I can't tell you guys how many hours I've spent on this one. I simply want to IGNORE any instances of keywords that are BETWEEN the strong tags. Whether they are directly next to the tags or somewhere in between with other words. All while keeping the keywords case-insensitive.
Example:
The man drove in his car. Then <strong>the man walked to the boat.</strong>
The word boat
should be ignored and Car
should be replaced.
$keywords = array(
'boat',
'car',
);
$p = implode('|', array_map('preg_quote', $keywords));
$string = preg_replace("/\b($p)\b/i", 'gokart', $string, 4);
You can use a SKIP-FAIL regex for to only replace something that is clearly outside on non-identical delimiters:
<strong>.*?<\/strong>(*SKIP)(*FAIL)|\b(boat|car)\b
See demo
Here is an IDEONE demo:
$str = "The man drove in his car.Then <strong>the man walked to the boat.</strong>";
$keywords = array('boat','car');
$p = implode('|', array_map('preg_quote', $keywords));
$result = preg_replace("#<strong>.*?<\/strong>(*SKIP)(*FAIL)|\b($p)\b#i", "gokart", $str);
echo $result;
NOTE that in this case, we most probably are not interested in a tempered greedy token solution inside the SKIP-FAIL block (that I posted initially, see revision history) since we do not care what is in between the delimiters.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With