注意:我使用的是较旧的 PHP 版本,因此
FILTER_VALIDATE_URL
目前不可用。
经过多次搜索后,我仍然无法找到可以涵盖所有 URL 结构可能性的确切答案,但最后我将使用这种方式:
我正在使用以下功能
1) 获得适当方案的功能
function convertUrl ($url){
$pattern = '#^http[s]?://#i';
if(preg_match($pattern, $url) == 1) { // this url has proper scheme
return $url;
} else {
return 'http://' . $url;
}
}
2) 有条件地检查它是否是一个 URL
if (preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i", $url)) {
echo "URL is valid";
}else {
echo "URL is invalid<br>";
}
你猜怎么着!?它非常适合所有这些可能性:
$url = "google.com";
$url = "www.google.com";
$url = "http://google.com";
$url = "http://www.google.com";
$url = "https://google.com";
$url = "https://www.codgoogleekarate.com";
$url = "subdomain.google.com";
$url = "https://subdomain.google.com";
但仍然有这个边缘案例
$url = "blahblahblahblah";
该函数convertUrl($url)
会将其转换为$url = "http://blahblahblahblah";
然后正则表达式将其视为有效 URL,而它不是!
我怎样才能编辑它,使它不会传递具有这种结构的 URLhttp://blahblahblahblah