如何确保字符串包含有效/格式良好的URL?

时间:2012-10-14 16:13:55

标签: php validation url

如何确保字符串包含有效/格式正确的网址?

我需要确保字符串中的url格式正确。

必须包含http://https://

.com.org.netany other valid extension

我尝试了SO中的一些答案,但所有人都认为“www.google.com”有效。

在我的情况下,有效网址必须是http:// www.google.com或https:// www.google.com。

www.部分不是义务,因为有些网址不使用它。

4 个答案:

答案 0 :(得分:3)

看看这里的答案: 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+!*(),;?&=\$_.-]+)?@)?"; // 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; 
       } 
?>

答案 1 :(得分:1)

您可以使用php filter_var函数

来完成此操作
$valid=filter_var($url, FILTER_VALIDATE_URL)

if($valid){
//your code
}

答案 2 :(得分:0)

有一个卷曲的解决方案:

function url_exists($url) {
    if (!$fp = curl_init($url)) return false;
    return true;
}

并且有一个fopen解决方案(如果你没有

function url_exists($url) {
    $fp = @fopen('http://example.com', 'r'); // @suppresses all error messages
    if ($fp) {
        // connection was made to server at domain example.com
        fclose($fp);
        return true;
    }
    return false;
}

答案 3 :(得分:0)

filter_var($url, FILTER_VALIDATE_URL)可以首先用于确保您处理有效的网址。

然后,您可以通过假设URL确实对parse_url有效来测试更多条件:

$res = parse_url($url);
return ($res['scheme'] == 'http' || $ret['scheme'] == 'https') && $res['host'] != 'localhost');
相关问题