如果在文本中找到某些单词/字符串,我想制作链接。我有一段来自 php.bet 的代码可以做到这一点,但它也从<a href="http://www.domain.com/index.php" title="Home">go to homepage</a>
. 你能帮忙解决这个问题吗?
这是一段代码:
<?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" title="首页"/a
“蠕虫”和“疾病”这两个词被转换成想要的链接,但其余的......
非常感谢!