如何使用PHP验证Vine URL并允许HTTP或HTTPS

时间:2014-12-11 17:43:09

标签: php validation url stripos

如何更改为允许Vine URL的HTTP或HTTPS?

$vineURL = 'https://vine.co/v/';
$pos = stripos($url_input_value, $vineURL);

if ($pos === 0) {
    echo "The url '$url' is a vine URL";
}
else {
    echo "The url '$url' is not a vine URL";
}

3 个答案:

答案 0 :(得分:3)

您可以使用parse_url功能,它会将URL分解为其组件,以便更轻松地单独匹配每个组件:

var_dump(parse_url("https://vine.co/v/"));
// array(3) {
//   ["scheme"]=>
//   string(4) "http"
//   ["host"]=>
//   string(7) "vine.co"
//   ["path"]=>
//   string(3) "/v/"
// }

然后,您只需检查schemehostpath是否匹配:

function checkVineURL($url) {
    $urlpart = parse_url($url);
    if($urlpart["scheme"] === "http" || $urlpart["scheme"] === "https") {
        if($urlpart["host"] === "vine.co" || $urlpart["host"] === "www.vine.co") {
            if(strpos($urlpart["path"], "/v/") === 0) {
                return true;
            }
        }
    }
    return false;
}
checkVineURL("https://vine.co/v/");     // true
checkVineURL("http://vine.co/v/");      // true
checkVineURL("https://www.vine.co/v/"); // true
checkVineURL("http://www.vine.co/v/");  // true
checkVineURL("ftp://vine.co/v/");       // false
checkVineURL("http://vine1.co/v/");     // false
checkVineURL("http://vine.co/v1/");     // false

答案 1 :(得分:1)

只需取出" https://"并稍微改变你的if陈述......就像这样:

$vineURL = 'vine.co/v/';
if(stripos($user_input_value, $vineURL) !== false) {
    echo "This is a vine URL";
} else {
    echo "This is not a vine URL";
}

答案 2 :(得分:0)

像这样的用户RegEx

if (preg_match("/^http(s)?:\/\/(www\.)?vine\.co\/v\//", $url)) {
    echo "This is a vine URL";
} else {
    echo "This is not a vine URL";
}