preg_replace替换匹配url的字符串

时间:2013-07-22 09:23:23

标签: php regex

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查找网址并设置此网址的链接。

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

但是以下网址格式没有被链接。

  1. http://www.google.com
  2. www.test.com()和[] &安培; ^%$#@ + | @#$%^&安培; ()_ +} {:!“&GT;&LT? ;,/;'[] = - 09〜`.CO,在,com.com
  3. http://www.test.com()和[] &安培; ^%$#@ + | @#$%^&安培; ()_ +} {:!” ?&GT;&LT;,/;'[] = - 09〜`.CO,在,com.com
  4. https://www.test.com()和[] &安培; ^%$#@ + | @#$%^&安培; ()_ +} {:!” ?&GT;&LT;,/;'[] = - 09〜`.CO,在,com.com
  5. ftp://www.test.com()和[] &安培; ^%$#@ + | @#$%^&安培; ()_ +} {:!” ?&GT;&LT;,/;'[] = - 09〜`.CO,在,com.com
  6. 我认为我的正则表达式有些错误。请建议我们。

1 个答案:

答案 0 :(得分:1)

我可以建议使用我的功能 - 只测试你的数据并为我工作

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作为第二个参数传递

相关问题