看看答案在这里做到这一点: PHP regex for url validation, filter_var is too permisive
filter_var()
可能只是对你罚款,但如果你需要更强大的东西,你将不得不使用正则表达式。
另外的代码从here,可以分在适合您需要的任何正则表达式:
<?php
$regex = "((https?|ftp)\:\/\/)?"; // SCHEME
$regex .= "([a-z0-9+!*(),;?&=\$_.-]+(\:[a-z0-9+!*(),;?&=\$_.-]+)[email protected])?"; // User and Pass
$regex .= "([a-z0-9-.]*)\.([a-z]{2,3})"; // Host or IP
$regex .= "(\:[0-9]{2,5})?"; // Port
$regex .= "(\/([a-z0-9+\$_-]\.?)+)*\/?"; // Path
$regex .= "(\?[a-z+&\$_.-][a-z0-9;:@&%=+\/\$_.-]*)?"; // GET Query
$regex .= "(#[a-z_.-][a-z0-9+\$_.-]*)?"; // Anchor
?>
Then, the correct way to check against the regex list as follows:
<?php
if(preg_match("/^$regex$/", $url))
{
return true;
}
?>
FILTER_VALIDATE_URL不是acceptible因为“本地主机”是一个有效的URL,但不能是我的系统上。 –