<?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;