テキストに見つかった場合、特定の単語/文字列をリンクのようにしたいと思います。私はそれを行うphp.betのコードを持っていますが、タグの先頭と末尾も<a href="http://www.domain.com/index.php" title="Home">go to homepage</a>
から削除します。これを解決するのに手伝ってくれますか?ここでPHPトークンがhtmlエンティティを置き換えます
は、コードの一部です:
<?php
$str_in = '<p>Hi there worm! You have a disease!</p><a href="http://www.domain.com/index.php" title="Home">go to homepage</a>';
$replaces= array(
'worm' => 'http://www.domain.com/index.php/worm.html',
'disease' => 'http://www.domain.com/index.php/disease.html'
);
function addLinks($str_in, $replaces)
{
$str_out = '';
$tok = strtok($str_in, '<>');
$must_replace = (substr($str_in, 0, 1) !== '<');
while ($tok !== false) {
if ($must_replace) {
foreach ($replaces as $tag => $href) {
if (preg_match('/\b' . $tag . '\b/i', $tok)) {
$tok = preg_replace(
'/\b(' . $tag . ')\b/i',
'<a title="' . $tag . '" href="' . $href . '">\1</a>',
$tok,
1);
unset($replaces[$tag]);
}
}
} else {
$tok = "<$tok>";
}
$str_out .= $tok;
$tok = strtok('<>');
$must_replace = !$must_replace;
}
return $str_out;
}
echo addLinks($str_in, $replaces);
結果は次のとおりです。
こんにちはワーム!あなたは病気です!
のhref =「http://www.domain.com/index.php」タイトル=「ホーム」/
「ワーム」と「病気」の言葉は、所望のようにリンクに変換され残りの部分は...
ありがとう!あなたはその大規模な建設を持っている理由
+1は、研究努力を示すよく考えられた質問です。 – Herbert