我想在文本中找到某些詞/字符串,如鏈接。我從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);
結果是:
您好蟲!你有一種疾病!
A HREF = 「http://www.domain.com/index.php」 標題= 「主頁」/一個
的 「蠕蟲」 和 「疾病」 字變換成鏈接等所需,但其餘...
非常感謝!
+1對於一個深思熟慮的問題,顯示研究工作量。 – Herbert