因为内容里可能已经带链接的html
所以需要先将链接的代码暂时隐藏,最后再恢复。
public static function text2link($str='')
{
if ($str == '' || !preg_match('/(http|ftp|www\.|@)/i', $str)) {
return $str;
}
$lines = explode("\n", $str . "\n");
$link = "";
foreach ($lines as $tt => $vv) {
$vv = preg_replace("/([ \r\n\t]|^)www\./i", "\\1http://www.", $vv); //www开头自动加http://
//将现有的链接代码隐藏
$vv = preg_replace_callback("/href=[\"|']((http|https|ftp):\/\/[^ \r\n]+)[\"|']/i", function ($matches) {
return "href=\"[link:". base64_encode($matches[1]) ."]\"";
}, $vv);
$vv = preg_replace("/((http|https|ftp):\/\/[^ \r\n]+)/i", "<a href=\"\\1\" target='_blank'>\\1</a>", $vv);
// $vv = preg_replace("/([-a-z0-9_]+(\.[_a-z0-9-]+)*@([a-z0-9-]+(\.[a-z0-9-]+)+))/i", "<a href=\"mailto:\\1\">\\1</a>", $vv);
//链接代码恢复
$vv = preg_replace_callback("/\[link:([^\]]+)\]/i", function ($matches) {
return base64_decode($matches[1]);
}, $vv);
$link .= $vv . "\n";
}
return $link;
}