用于匹配 php 字符串中的 http 和 www url 的正则表达式
regex for matching http and www urls in a php string
这是我正在使用的代码
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;
}
出于某种原因,我的正则表达式输出以下结果:(粗体 = 链接)
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='[=12=]' target='_blank'>[=12=]</a>";
$text = preg_replace($regex, $subst, $text);
return $text;
}
您不需要先收集匹配项,然后逐个替换。直接使用 preg_replace
并使用 [=13=]
反向引用来引用替换模式中的整个匹配项。
参见PHP demo:
$re = '@\b(([\w-]+://?|www[.])[^\s()<>]+(?:\(\w+\)|([^[:punct:]\s]|/)))@i';
$str = "www.domain.com\nhttp://www.domain.com\nhttp://domain.com";
$subst = '<a href="[=10=]" target="_blank">[=10=]</a> ';
$result = preg_replace($re, $subst, $str);
echo $result;
输出:
<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>
这是我正在使用的代码
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;
}
出于某种原因,我的正则表达式输出以下结果:(粗体 = 链接)
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='[=12=]' target='_blank'>[=12=]</a>";
$text = preg_replace($regex, $subst, $text);
return $text;
}
您不需要先收集匹配项,然后逐个替换。直接使用 preg_replace
并使用 [=13=]
反向引用来引用替换模式中的整个匹配项。
参见PHP demo:
$re = '@\b(([\w-]+://?|www[.])[^\s()<>]+(?:\(\w+\)|([^[:punct:]\s]|/)))@i';
$str = "www.domain.com\nhttp://www.domain.com\nhttp://domain.com";
$subst = '<a href="[=10=]" target="_blank">[=10=]</a> ';
$result = preg_replace($re, $subst, $str);
echo $result;
输出:
<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>