PHP 使用preg_replace替换字符串中的url,即使没有http://

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PHP 使用preg_replace替换字符串中的url,即使没有http://相关的知识,希望对你有一定的参考价值。

<?php
// this function shall search for any url that matches the pattern
// like:
// www.mysite.com
// http://www.mysite.com
// http://mysite.com
// those urls shall be replaced by a html link tag

$text= preg_replace('@((https?://)?([-\w]+\.[-\w\.]+)+\w(:\d+)?(/([-\w/_\.]*(\?\S+)?)?)*)@', '<a href="$1" target="blank">$1</a>', $text);

//because you want the url to be an external link the href needs to start with 'http://'
//simply replace any occurance of 'href="www.' into 'href="http://www."

$status = str_replace("href=\"www.","href=\"http://www.",$status);

以上是关于PHP 使用preg_replace替换字符串中的url,即使没有http://的主要内容,如果未能解决你的问题,请参考以下文章