I am trying to implement automatic hyperlink function for keywords.
The issue I am having that a keyword can be a part of other keyword. For example: potato, sweet potato. The function has to know not to hyperlink potato in sweet potato..
I am using regex and it actually works on different environments but not in my localhost and not in live version..
Working example:
$keywords_external = 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'
);
foreach($keywords_external as $key => $href)
{
$regex = '/<a\b(?=\s)(?:[^>=]|=\'[^\']*\'|="[^"]*"|=[^\'"\s]*)*"\s?>.*?<\/a>|('.$key.')/ims';
$data['post_content'] = preg_replace_callback(
$regex,
function ($matches) {
if (array_key_exists (1, $matches)) {
return '<a href="https://example.com/">'. $matches[1] .'</a>';
}
return $matches[0];
},
$data['post_content']
);
}
echo $data['post_content'];
Works on http://phpfiddle.org
Same example does not work in live version..
Any ideas to achieve same thing differently or why it does not might work in live version?
Thanks.
PHP VERSIONS
Localhost: PHP Version 7.0.12,
Live: PHP Version 7.0.15-1+deb.sury.org~xenial+1,
Live which works: PHP Version 5.4.45