I need to validate a URL field for an input field that deals with a finicky API that will accept URL strings in a very certain format - no www's and no http's attached to the start of the string, or it breaks. A javascript handler grabs the data from the validation.php file. I have everything working except for one field.
So, for example I want
example.com/example
and
example.com
to pass validation, but I want
and
and any variation including any derivation of http:// or www. to not validate.
The regex I have below currently allows any type of URL including http and www. I want it to ONLY allow the above type of URL string, but not sure how to go about this.
// API URL VALIDATION
if ($formfield == "api_url") {
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i", $value)) {
echo "Please enter your URL without the http://www part attached"
} else {
echo "<span>Valid</span>";
}
}
Any ideas?
You can use this simple negative lookahead based regex in preg_match
:
~^(?!https?://)(?!www\.).+$~i
您可以尝试“不匹配”以http或www开头的主题:
if(!preg_match('/^((http|ftp)s?:\/\/)?(www\.).+?/', $value))
You can do it with .htaccess
mod rewrite
rule. But in your case it looks like you need to validate a input field so it doesn't apply to all cases. Here is function which will allow/dis-allow such protocols in the url.
function remove_protocol($url) {
$filter_protocol = array('http://', 'https://', 'http://www');
foreach($filter_protocol as $d) {
if(strpos($url, $d) === 0) {
return str_replace($d, '', $url);
}
}
return $url;
}
in the $filter_protocol
array you can keep on defining protocols not to allow in urls for instance ftp://
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.