我想提出一個JSON驗證,需要驗證URL以http://或https://開頭PHP驗證(兩個條件)
if(preg_match("/^[http://][a-zA-Z -]+$/", $_POST["url"]) === 0)
if(preg_match("/^[https://][a-zA-Z -]+$/", $_POST["url"]) === 0)
我錯在synatx,還我應該如何在同一個語句中同時包含(http和https)?
謝謝!
我想提出一個JSON驗證,需要驗證URL以http://或https://開頭PHP驗證(兩個條件)
if(preg_match("/^[http://][a-zA-Z -]+$/", $_POST["url"]) === 0)
if(preg_match("/^[https://][a-zA-Z -]+$/", $_POST["url"]) === 0)
我錯在synatx,還我應該如何在同一個語句中同時包含(http和https)?
謝謝!
$isHttps = (isset($_SERVER['HTTPS']) && !empty($_SERVER['HTTPS']) ? true : false;
可以使用parse_url
<?php
$url = parse_url($_POST["url"]);
if($url['scheme'] == 'https'){
// is https;
}else if($url['scheme'] == 'http'){
// is http;
}
// try to do this, so you can know what is the $url contains
echo '<pre>';print_r($url);echo '</pre>';
?>
OR
<?php
if (substr($_POST["url"], 0, 7) == "http://")
$res = "http";
if (substr($_POST["url"], 0, 8) == "https://")
$res = "https";
?>
如果要檢查你的字符串的http://開頭或HTTPS ://而不必擔心整個URL的有效性,只要做到這一點:
<?php
if (preg_match('`^https?://.+`i', $_POST['url'])) {
// $_POST['url'] starts with http:// or https://
}
希望此鏈接將幫助您: https://stackoverflow.com/questions/6427530/regular-expression-pattern-to-match- url-with-or-without-http-www –
你可以使用這個:https://regex101.com/r/Ciafhq/1 – C2486