我对PHP中的URL验证进行了一些研究,发现StackOverflow上有许多不同的答案,有些比其他答案更好,有些则非常古老和过时。
我有一个字段,用户可以在其中输入其网站的网址。用户应该能够以任何形式输入 URL,例如:
example.com
www.example.com
http://example.com
http://www.example.com
https://example.com
https://www.example.com
PHP 带有一个验证 URL 的功能,但是,如果没有 http://
,它会将 URL 标记为无效。
如何验证任何类型的 URL,无论是否带有http://
或https://
,以确保 URL 有效?
谢谢。
如您所述使用filter_var()
,但是,根据定义,URL必须包含协议。 仅使用 http
也会检查https
:
$url = strpos($url, 'http') !== 0 ? "http://$url" : $url;
然后:
if(filter_var($url, FILTER_VALIDATE_URL)) {
//valid
} else {
//not valid
}
我也看到过这个用法:
$url = "http://example.com";
if (preg_match("/'b(?:(?:https?|ftp):'/'/|www'.)[-a-z0-9+&@#'/%?=~_|!:,.;]*[-a-z0-9+&@#'/%=~_|]/i", $url)) {
echo "URL is valid";
}
else {
echo "URL is invalid";
}
来源: http://codekarate.com/blog/validating-url-php
您可以创建自定义验证规则,然后在其中添加以下方法:
protected function prepareForValidation()
{
$urlWithHttp = strpos($this->url, 'http') !== 0 ? "http://$this->url" : $this->url;
$this->merge([
'url' => $urlWithHttp,
]);
}
你也可以
让html验证网址:
Website: <input type="url" name="website" required pattern="https?://.+">