<?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 . '">' . $m[0] . '</a>';
}, $data['post_content']);
echo $result;
Warning: Array to string conversion in /in/Ye8ec on line 25
Warning: Array to string conversion in /in/Ye8ec on line 25
Warning: Array to string conversion in /in/Ye8ec on line 25
<a href="http://domain.com/Array">Sweet potato</a> some text then <a href="http://domain.com/Array">potato</a> then more text and then <a href="http://domain.com/Array">potato</a> salads
Output for 8.3.5
Warning: PHP Startup: Unable to load dynamic library 'sodium.so' (tried: /usr/lib/php/8.3.5/modules/sodium.so (libsodium.so.23: cannot open shared object file: No such file or directory), /usr/lib/php/8.3.5/modules/sodium.so.so (/usr/lib/php/8.3.5/modules/sodium.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0
Warning: Array to string conversion in /in/Ye8ec on line 25
Warning: Array to string conversion in /in/Ye8ec on line 25
Warning: Array to string conversion in /in/Ye8ec on line 25
<a href="http://domain.com/Array">Sweet potato</a> some text then <a href="http://domain.com/Array">potato</a> then more text and then <a href="http://domain.com/Array">potato</a> salads
Notice: Array to string conversion in /in/Ye8ec on line 25
Notice: Array to string conversion in /in/Ye8ec on line 25
Notice: Array to string conversion in /in/Ye8ec on line 25
<a href="http://domain.com/Array">Sweet potato</a> some text then <a href="http://domain.com/Array">potato</a> then more text and then <a href="http://domain.com/Array">potato</a> salads
Output for 7.3.32 - 7.3.33, 7.4.26
<a href="http://domain.com/Array">Sweet potato</a> some text then <a href="http://domain.com/Array">potato</a> then more text and then <a href="http://domain.com/Array">potato</a> salads