文字列内の単語を検索してリンクする簡単な関数を作成しようとしています。問題は、単語の末尾にドットまたはコンマが含まれている場合があり、それを保持したいということです。text word.
に変更する必要がありtext <a href="#">word</a>.
ます。text <a href="#">word</a>
これが今までの私の機能です。機能しない理由がわかりません:
$string = "words are plenty in the world. another world and another world,comma.";
function findWord ($string, $word, $link) {
$patt = "/(?:^|[^a-zA-Z])(" . preg_quote($word, '/') . ")(?:$|[^a-zA-Z])/i";
return preg_replace($patt, ' <a href="'.$link.'" class="glossary-item">'.$word.'</a>$3', $string);
}
echo findWord ($string, "world", "#");