preg_replace替换匹配 url 的字符串


preg_replace to replace string for matching url

function makeLinksInTheContent($html)
{
    $html= preg_replace("/(^|['n ])(['w]*?)((ht|f)tp(s)?:'/'/['w]+[^ ','"'n'r't<]*)/is", "$1$2<a href='"$3'" rel='"nofollow'" >$3</a>", $html);
    $html= preg_replace("/(^|['n ])(['w]*?)((www|ftp)'.[^ ','"'t'n'r<]*)/is", "$1$2<a href='"http://$3'" rel='"nofollow'" >$3</a>", $html);
    $html= preg_replace("/(^|['n ])([a-z0-9&'-_'.]+?)@(['w'-]+'.(['w'-'.]+)+)/i", "$1<a href='"mailto:$2@$3'" rel='"nofollow'">$2@$3</a>", $html);
    return($html);
}

这是我的代码。

我需要自动链接网址。使用preg_replace查找 URL 并设置指向此 URL 的链接。

例如:"一个页面包含 www.google.com",如果我将此内容传递给makeLinksInTheContent($html(,它将返回"一个页面包含 www.google.com"。

但是以下 url 格式未链接。

  1. (http://www.google.com(
  2. www.test.com((and[]&^%$#@!+|!@#$%^&((_+}{:"?><,./;'[]=-09~'.co,in,com.com
  3. http://www.test.com((and[]&^%$#@!+|!@#$%^&((_+}{:"?><,./;'[]=-09~'.co,in,com.com
  4. https://www.test.com((and[]&^%$#@!+|!@#$%^&((_+}{:"?><,./;'[]=-09~'.co,in,com.com
  5. ftp://www.test.com((and[]&^%$#@!+|!@#$%^&((_+}{:"?><,./;'[]=-09~'.co,in,com.com

我认为我的正则表达式有一些错误。 请推荐我们。

我可以建议使用我的函数 - 刚刚用您的数据进行了测试并适合我

function parse_links($string,$mailto=true)
{
    $preg_r = "#(((https?|ftp)(://)?)?[a-zA-Z0-9-_.]{1,64}'.[a-zA-Z0-9-_.]{1,128}'.[a-z]{2,4}('.[a-z]{2,4})?(/([^ ]{1,256}))?/?)#";
    $string = preg_replace($preg_r,"<a href='"http://$1'">$1</a>",explode(" ",$string));
    if($mailto)
    {
        $preg_r2 = "/([0-9a-zA-Z]([-.'w]*[0-9a-zA-Z])*@([0-9a-zA-Z_'-'.][-'w]*[0-9a-zA-Z_'-'.]'.)+[a-zA-Z]{2,9})/";
        $string = preg_replace($preg_r2,"<a href='"mailto:$1'">$1</a>",$string);
    }
    return implode(" ",$string);
}

如果您不希望创建电子邮件链接,只需将false作为第二个参数传递即可