有些人可能不明白标题意思,简单通俗的讲就是把字符串里的网址转为超链接显示。我们用PHP写了个函数,只要传参变量文本,即可自动转换。
字符串锚文本转换为可点击的链接函数:function urlToLink($str) { <br>
$arr = array("www." => "http://www."); <br>
$str = strtr($str, $arr); <br>
$arr = array("http://http://" => "http://"); <br>
$str = strtr($str, $arr); <br>
$str2 = explode("http://", $str); <br>
for ($n = 1; isset($str2[$n]); $n ++) { <br>
$str3 = explode(".", $str2[$n]); <br>
if (isset($str3[1])) { <br>
$str4 = explode("www.", $str2[$n]); <br>
if ((isset($str4[1]) && isset($str3[2])) || !isset($str4[1])) { <br>
$length = strlen($str2[$n]); <br>
for ($i = 0; $i
//从空格断开 <br>
if (($i - 1) == strlen(trim(mb_substr($str2[$n], 0, $i, 'gb2312')))) { <br>
$ii = $i - 1; <br>
$url1 = mb_substr($str2[$n], 0, $ii, 'gb2312'); <br>
$url2 = mb_substr($str2[$n], $ii, $length, 'gb2312'); <br>
$url3 = "<a>http://" . $url1 . "</a>" . $url2; <br>
break; <br>
} <br>
<br>
//从出现汉字处断开 <br>
if ($i != strlen(mb_substr($str2[$n], 0, $i, 'gb2312'))) { <br>
$ii = $i - 1; <br>
$url1 = mb_substr($str2[$n], 0, $ii, 'gb2312'); <br>
$url2 = mb_substr($str2[$n], $ii, $length, 'gb2312'); <br>
$url3 = "<a>http://" . $url1 . "</a>" . $url2; <br>
break; <br>
} <br>
if ($i == $length) <br>
$url3 = "<a>http://" . $str2[$n] . "</a>"; <br>
} <br>
} else <br>
$url3 = "http://" . $str2[$n]; <br>
} else <br>
$url3 = "http://" . $str2[$n]; <br>
$url .= $url3; <br>
} <br>
if (substr($str, 0, 7) == "http://") <br>
$url = "<a>" . $str2[0] . "</a>" . $url; <br>
else <br>
$url = $str2[0] . $url; <br>
return $url; <br>
}
若是还不明白,不妨看看演示地址http://www.sucaihuo.com/php/568.html的前后对比效果,一看就明白。
PHP文本链接转换成超链接.zip ( 2.14 KB 下载:16 次 )
AD:真正免费,域名+虚机+企业邮箱=0元