Вам необходимо использовать preg_replace с \b
. Это ограничит замену полными словами.
Я использую implode для построения шаблона регулярных выражений, чтобы он выглядел как:
"\b(another example)|(examples)|(example)\b/"
Затем замена использует то, что фиксирует регулярное выражение.
$replacement = [
'another example' => 'http://another-example.com',
'examples' => 'http://examples.com',
'example' => 'http://example.com',
];
$content = "Two examples are the combination of an example and another example.";
echo preg_replace("/\b(". implode(")|(", array_keys($replacement)) . ")\b/", "<a href=\"$0\">$0</a>", $content);
Выход:
Two <a href="examples">examples</a> are the combination of an <a href="example">example</a> and <a href="another example">another example</a>.
https://3v4l.org/1Jhak
Чтобы получить бонус для работы, нам нужно использовать четвертый аргумент preg_replace и зациклить массив.
Это ограничивает preg_replace только одной заменой.
$replacement = [
'another example' => 'http://another-example.com',
'examples' => 'http://examples.com',
'example' => 'http://example.com',
];
$content = "Two examples are the combination of an example and another example,
Two examples are the combination of an example and another example.";
foreach($replacement as $find => $repl){
$content = preg_replace("/\b(". $find . ")\b/", "<a href=\"$repl\">$0</a>", $content, 1);
}
echo $content;
Выход:
Two <a href="http://examples.com">examples</a> are the combination of an <a href="http://example.com">example</a> and <a href="http://another-example.com">another example</a>,
Two examples are the combination of an example and another example.
https://3v4l.org/8GFZr