0

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

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

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

.com.org.netany other valid extension

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

在我的情况下,有效的 url 需要是http://www.google.com 或https://www.google.com。

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

4

4 回答 4

3

看看这里的答案: PHP regex for url validation, filter_var is too permissive

filter_var()可能对您来说很好,但是如果您需要更强大的功能,则必须使用正则表达式。

此外,使用此处的代码,您可以分入任何适合您需要的正则表达式:

<?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; 
       } 
?>
于 2012-10-14T16:18:41.397 回答
1

你可以通过使用 phpfilter_var函数来做到这一点

$valid=filter_var($url, FILTER_VALIDATE_URL)

if($valid){
//your code
}
于 2012-10-14T16:18:02.320 回答
0

有一个 curl 解决方案:

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;
}
于 2012-10-14T16:20:56.210 回答
0

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

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

$res = parse_url($url);
return ($res['scheme'] == 'http' || $ret['scheme'] == 'https') && $res['host'] != 'localhost');
于 2012-10-14T16:23:24.383 回答