3v4l.org

run code in 200+ php & hhvm versions
Bugs & Features
<?php // all keys must be lowercase $keywords_external_path = array( "sweet potato" => "food/sweet-potato", "potato salads" => "food/potato-salads", "potato" => "food/potato", ); $data = array( 'post_content' => 'Sweet potato some text then potato then more text and then potato salads' ); $base = 'http://domain.com/'; // only if this is useful $keywords_external = array_keys($keywords_external_path); krsort($keywords_external); // to quickly discards useless position (if you have many keywords): you can also do the same with the second letter $keywords_first_letter = implode('', array_unique(array_reduce($keywords_external, function ($c, $i) { $c[]=$i[0]; return $c; }, []))); $pattern = '~\b(?=['. $keywords_first_letter . '])(?:' . implode('|', $keywords_external) . ')\b~i'; $result = preg_replace_callback($pattern, function ($m) use ($keywords_external_path, $base) { return '<a href="' . $base . $keywords_external_path[strtolower($m[0])] . '">' . $m[0] . '</a>'; }, $data['post_content']); echo $result;
based on Ye8ec
Output for 5.6.0 - 5.6.30, hhvm-3.15.4, 7.0.0 - 7.3.0rc3
<a href="http://domain.com/food/sweet-potato">Sweet potato</a> some text then <a href="http://domain.com/food/potato">potato</a> then more text and then <a href="http://domain.com/food/potato">potato</a> salads