【发布时间】:2016-09-14 23:51:15
【问题描述】:
This is a link to the String in a linter.
这就是表达式本身:
(?i)\b((?:https?:\/\/|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»“”‘’]))
我正在尝试使用此表达式验证几乎任何 Web url。
我们可以在这里看到它按预期通过了单元测试:
然而正如我所说,当我尝试运行我的代码时,它似乎忽略了验证......让我摸不着头脑。
这些是代码的相关部分:
//kindly taken from here: http://stackoverflow.com/a/34589895/2226328
function checkPageSpeed($url){
if (function_exists('file_get_contents')) {
$result = @file_get_contents($url);
}
if ($result == '') {
$ch = curl_init();
$timeout = 60;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER,1);//get the header
curl_setopt($ch, CURLOPT_NOBODY,1);//and *only* get the header
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);//get the response as a string from curl_exec(), rather than echoing it
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_FRESH_CONNECT,1);//don't use a cached version of the url
$result = curl_exec($ch);
curl_close($ch);
}
return $result;
}
function pingGoogle($url){
echo "<h1>".$url."</h1>";
if(strtolower(substr($url, 0, 4)) !== "http") {
echo "adding http:// to $url <br/>";
$url = "http://".$url;
echo "URL is now $url <br/>";
}
//original idea from https://gist.github.com/dperini/729294
$re = "/(?i)\\b((?:https?:\\/\\/|www\\d{0,3}[.]|[a-z0-9.\\-]+[.][a-z]{2,4}\\/)(?:[^\\s()<>]+|\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\))+(?:\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\)|[^\\s`!()\\[\\]{};:'\\\".,<>?«»“”‘’]))/";
$test = preg_match($re, $url);
var_export($test);
if( $test === 1) {
echo "$url passes pattern Test...let's check if it's actually valid ...";
pingGoogle("hjm.google.cm/");
pingGoogle("gamefaqs.com");
}
else
{
echo "URL formatted proper but isn't an active URL! <br/>";
}
}
【问题讨论】:
-
可能是您拥有的 === 而不是 == 吗?请看这里stackoverflow.com/questions/1117967/what-does-mean。尝试将其更改为 == 看看会发生什么。
-
@Remuze 仍然有相同的结果......我也从 sublimetext 中得到了有趣的格式问题......但如果它实际上只是程序或问题的话:puu.sh/oWlBI/fcef09bfc4.png
-
我可能在这里遗漏了一些东西,但为什么屏幕截图中有单反斜杠,而 PHP 代码中有双反斜杠? `\` 不会转义反斜杠吗?
-
不太确定,他们不在这里了,我可能在正则表达式 linter 中弄乱了它,然后再将其粘贴回我的代码中
-
您可能想要更新您的代码以反映这一点:)