【发布时间】:2011-09-15 19:18:21
【问题描述】:
如果在文本中找到某些单词/字符串,我想制作链接。我有一段来自 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
“蠕虫”和“疾病”这两个词被转换成想要的链接,但其余的......
非常感谢!
【问题讨论】:
-
+1 表示研究工作经过深思熟虑的问题。