<pre name="code" class="php"> public function formatUrlsInText($str){
preg_match_all('/((http|ftp|https):\/\/)?([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:\/~+#-]*[\w@?^=%&\/~+#-])?/',$str,$arr);
if(!$arr[0])
{
return $str;
}
$replaceOnce = function ($needle, $replace, $haystack){
$pos = strpos($haystack, $needle);
if ($pos === false) {return $haystack;}
return substr_replace($haystack, $replace, $pos, strlen($needle));
};
$_tmp = [];
foreach ($arr[0] as $v)
{
$tmp = explode($v,$str);
$_tmp[]=$tmp[0];
$_tmp[]="<a href='{$v}' target='_blank'>{$v}</a>";
$str = $replaceOnce($tmp[0].$v,'',$str);
}
return join($_tmp,' ');
}
$str = "你好http://write.blog.csdn.net/postedit?ref=toolbar&ticket=ST-99072-bM4IbtB2YfATabC70Q4Q-passport.csdn.net呵呵哒www.qq.com嗯嗯baidu.com";
echo urlToLink($str);
结果:
你好 http://write.blog.csdn.net/postedit?ref=toolbar&ticket=ST-99072-bM4IbtB2YfATabC70Q4Q-passport.csdn.net 呵呵哒www.qq.com 嗯嗯baidu.com