私は、いくつかの単語が説明されている用語集を含む Web サイトに取り組んでいます。さらに、タイトル属性を使用してスパンに入れ、記事内の用語を説明したいと考えています。
データベースからすべての用語を配列で取得します。
$terms = array(
'word1' => 'This is a short description of word1',
'word2' => 'word2 maybe has something to do with word1'
);
テキストを含む文字列は次のようになります。
$string = 'In this sentence I want to explain both, word1 and word2.';
文字列に含まれる単語を単純な str_ireplace() で単純に置き換えようとしました。
foreach($terms as $term => $description)
{
$string = str_ireplace($term, '<span class="help" title="' . $description . '">' . $term . '</span>', $string);
}
これで、word1 と word2 が正しく置き換えられます。しかし、テキストを 2 回繰り返して word2 を検索して置換すると、既に作成されたスパンのタイトルで word1 が再び検出されます。
したがって、word1 の結果は次のようになります。
<span class="help" title="This is a short description of <span class="help" title="This is a short description of word1">word1</span>word1</span>
PHP が既存のスパンのタイトル タグ内の同じ単語を置き換えないようにするにはどうすればよいですか? そのために preg_replace() を使用したくありません。html を解析しないためです。
どうすればそれができますか?
ドイツからの素敵な挨拶 クリス