要匹配大多数URL,regex正则表达式需要改进


regex regular expression to match most of URLs needs improvement

我需要一个函数来检查字符串中的现有URL。

function linkcleaner($url) {
$regex="(?i)'b((?:[a-z]['w-]+:(?:/{1,3}|[a-z0-9%])|www'd{0,3}[.]|[a-z0-9.'-]+[.][a-z]{2,4}/)(?:[^'s()<>]+|'(([^'s()<>]+|('([^'s()<>]+')))*'))+(?:'(([^'s()<>]+|('([^'s()<>]+')))*')|[^'s`!()'[']{};:'".,<>?«»“”‘’]))";
if(preg_match($regex, $url, $matches)) {
echo $matches[0];
}
}

正则表达式取自John Gruber的博客,他在博客中解决了创建一个匹配所有URL的正则表达式的问题。不幸的是,我不能让它工作。问题似乎来自正则表达式中的双引号或表达式末尾的其他标点符号。感谢您的帮助。非常感谢。

您需要使用' 逃离"

除了@tandu的答案外,您还需要php中正则表达式的分隔符。

最简单的方法是用#开始和结束你的模式,因为这个字符没有出现在其中:

$regex="#(?i)'b((?:[a-z]['w-]+:(?:/{1,3}|[a-z0-9%])|www'd{0,3}[.]|[a-z0-9.'-]+[.][a-z]{2,4}/)(?:[^'s()<>]+|'(([^'s()<>]+|('([^'s()<>]+')))*'))+(?:'(([^'s()<>]+|('([^'s()<>]+')))*')|[^'s`!()'[']{};:'''".,<>?«»“”‘’]))#";
Jack Maney的评论。。。史诗:D

更严重的是,它不起作用,因为您在在中间终止了字符串文字。

要在字符串中包含双引号("),需要使用' 对其进行转义

所以,这条线将是

$regex="/(?i)'b((?:[a-z]['w-]+:(?:/{1,3}|[a-z0-9%])|www'd{0,3}[.]|[a-z0-9.'-]+[.][a-z]{2,4}/)(?:[^'s()<>]+|'(([^'s()<>]+|('([^'s()<>]+')))*'))+(?:'(([^'s()<>]+|('([^'s()<>]+')))*')|[^'s`!()'[']{};:'''".,<>?«»“”‘’]))/";

注意,我也逃离了(')。这适用于定义两个单引号之间的字符串。

我不确定你们是如何阅读这个正则表达式的,因为阅读/修改它真的很痛苦…;)

试试这个(是的,这不是一句话,但如果需要的话,它很容易理解和修改):

<?php
$re_proto = "(?:https?|ftp|gopher|irc|whateverprotoyoulike)://";
$re_ipv4_segment = "[12]?[0-9]{1,2}";
$re_ipv4 = "(?:{$re_ipv4_segment}[.]){3}".$re_ipv4_segment;
$re_hostname = "[a-z0-9_]+(?:[.-][a-z0-9_]+){0,}";
$re_hostname_fqdn = "[a-z0-9_](?:[a-z0-9_-]*[.][a-z0-9]+){1,}";
$re_host = "(?:{$re_ipv4}|{$re_hostname})";
$re_host_fqdn = "(?:{$re_ipv4}|{$re_hostname_fqdn})";
$re_port = ":[0-9]+";
$re_uri = "(?:/[a-z0-9_.%-]*){0,}";
$re_querystring = "[?][a-z0-9_.%&=-]*";
$re_anchor = "#[a-z0-9_.%-]*";
$re_url = "(?:(?:{$re_proto})(?:{$re_host})|{$re_host_fqdn})(?:{$re_port})?(?:{$re_uri})?(?:{$re_querystring})?(?:{$re_anchor})?";
$text = <<<TEXT
http://www.example.com
http://www.example.com/some/path/to/file.php?f1=v1&f2=v2#foo
http://localhost.localdomain/
http://localhost/docs/???
www....wwhat?
www.example.com
ftp://ftp.mozilla.org/pub/firefox/latest/
Some new Mary-Kate Olsen pictures I found: the splendor of the Steiner Street Picture of href… http://t.co/tJ2NJjnf
TEXT;
$count = preg_match_all("'01{$re_url}'01is", $text, $matches);
var_dump($count);
var_dump($matches);
?>