用于在php字符串中匹配http和www URL的正则表达式

用于在php字符串中匹配http和www URL的正则表达式,php,regex,preg-match-all,Php,Regex,Preg Match All,这是我正在使用的代码 function parseURL($text) { $regex = "#\b(([\w-]+://?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/)))#iS"; preg_match_all($regex, $text, $matches); foreach($matches[0] as $pattern){ $text = str_replace($patter

这是我正在使用的代码

function parseURL($text) {
    $regex = "#\b(([\w-]+://?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/)))#iS";
    preg_match_all($regex, $text, $matches);
    foreach($matches[0] as $pattern){
        $text = str_replace($pattern, "<a href=\"$pattern\" target=\"_blank\">$pattern</a> ", $text);   
    }
    return $text;
}
函数parseURL($text){
$regex=“#b”([\w-]+:/?| www[.])[^\s()]+(?:\([\w\d]+\)|([^[:punct:][\s]|/)))#iS”;
preg_match_all($regex,$text,$matches);
foreach($matches[0]为$pattern){
$text=str_replace($pattern,“,$text);
}
返回$text;
}
出于某种原因,我的正则表达式正在输出以下结果:(粗体=链接)

www.domain.com

http://www.domain.com

因此,它工作得很好,除非它同时包含http和www,此时它只从www部分开始链接

知道为什么吗

编辑

对于需要修复的读者,这里是工作代码,感谢Wiktor Stribiżew

function parseURL($text) {
    $regex = "@\b(([\w-]+://?|www[.])[^\s()<>]+(?:\(\w+\)|([^[:punct:]\s]|/)))@i";
    $subst = "<a href='$0' target='_blank'>$0</a>";
    $text = preg_replace($regex, $subst, $text);
    return $text;
}
函数parseURL($text){
$regex=“@\b([\w-]+:/?;www[.])[^\s()]+(?:\(\w+\)|([^[:punct:][\s]|/)@i”;
$subst=“”;
$text=preg_replace($regex,$subst,$text);
返回$text;
}

您不需要先收集匹配项,然后逐个替换。直接使用
preg_replace
并使用
$0
反向引用引用替换模式中的整个匹配项

见:

$re='@\b(([\w-]+:/?)[^\s()]+(?:\(\w+\)|([^[:punct:\s]./))@i';
$str=“www.domain.com\nhttp://www.domain.com\nhttp://domain.com";
$subst='';
$result=preg_replace($re,$subst,$str);
回声$结果;
输出:

<a href="www.domain.com" target="_blank">www.domain.com</a> 
<a href="http://www.domain.com" target="_blank">http://www.domain.com</a> 
<a href="http://domain.com" target="_blank">http://domain.com</a> 


为什么要替换匹配项?直接使用
preg\u replace
。而且,
S
在这里没有任何意义(即使您打算使用
S
,DOTALL)。看到了吗?有什么原因,为什么不使用?@Anant当$text中有多个url时string@WiktorStribiżew-啊,是的,我已经尝试了很长时间,我忘了我在使用strżu替换,这是我的问题!谢谢,我的问题现在解决了。
<a href="www.domain.com" target="_blank">www.domain.com</a> 
<a href="http://www.domain.com" target="_blank">http://www.domain.com</a> 
<a href="http://domain.com" target="_blank">http://domain.com</a>