我需要为一个输入字段验证一个URL字段,该字段处理一个挑剔的API,该API将接受非常特定格式的URL字符串-字符串的开头没有www和http,否则它会断开。javascript处理程序从validation.php文件中获取数据。除了一块地,我什么都干。
例如,我想要
example.com/example
和
example.com
通过验证,但我想要
http://example.com/example
和
http://www.example.com/example
以及任何变体,包括http://或www.的任何派生,以不进行验证。
我下面的正则表达式目前允许任何类型的URL,包括http和www.。我希望它只允许上面类型的URL字符串,但不确定如何进行。
// 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>";
}
}
有什么想法吗?
您可以在preg_match
:中使用这个简单的基于负前瞻的正则表达式
~^(?!https?://)(?!www'.).+$~i
RegEx演示
您可以尝试"不匹配"以http或www开头的主题:
if(!preg_match('/^((http|ftp)s?:'/'/)?(www'.).+?/', $value))
您可以使用.htaccess
mod rewrite
规则来执行此操作。但在您的情况下,似乎需要验证输入字段,因此它不适用于所有情况。这是一个允许/不允许在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;
}
在$filter_protocol
数组中,您可以继续定义不允许在URL中使用的协议,例如ftp://