PHP正则表达式不允许URL过短

PHP正则表达式不允许URL过短,php,regex,preg-replace,Php,Regex,Preg Replace,我有一个正则表达式,可以在文本中查找URL并用链接替换它们 preg_replace( '@(?<![.*">])\b(?:(?:https?|ftp|file)://|[a-z]\.)[-A-Z0-9+&#/%=~_|$?!:,.]*[A-Z0-9+&#/%=~_|$]@i', '<a href="\0" target="_blank" rel="nofollow">\0</a>', $text ); 您可以使用preg\u replace

我有一个正则表达式,可以在文本中查找URL并用链接替换它们

preg_replace( '@(?<![.*">])\b(?:(?:https?|ftp|file)://|[a-z]\.)[-A-Z0-9+&#/%=~_|$?!:,.]*[A-Z0-9+&#/%=~_|$]@i', '<a href="\0" target="_blank" rel="nofollow">\0</a>', $text );

您可以使用
preg\u replace\u callback
检查捕获的文本是否至少包含
5
6
字符:

preg_replace_callback( '@(?<![.*">])\b(?:(?:https?|ftp|file)://|[a-z]\.)([-A-Z0-9+&#/%=~_|$?!:,.]{3,})*[A-Z0-9+&#/%=~_|$]@i', function($matches){
   if(strlen($matches[0])>5){
      return '<a href="'.$matches[0].'" target="_blank" rel="nofollow">'.$matches[0].'</a>';
    }else{
       return $matches[0];
     }
   }, $text );

preg_replace_callback(@(?太好了,它很管用了!大家记住,如果你把这段代码包装在像text_to_url($text)这样的函数中,那么在preg_replace_callback前面放上“return”,当然,如果你包装它,你就必须放上return语句。但这不是你的问题
preg_replace_callback( '@(?<![.*">])\b(?:(?:https?|ftp|file)://|[a-z]\.)([-A-Z0-9+&#/%=~_|$?!:,.]{3,})*[A-Z0-9+&#/%=~_|$]@i', function($matches){
   if(strlen($matches[0])>5){
      return '<a href="'.$matches[0].'" target="_blank" rel="nofollow">'.$matches[0].'</a>';
    }else{
       return $matches[0];
     }
   }, $text );