我们如何通过使用正则表达式来验证网站网址。
网址是这样的:
google.com
www.google.com
http://google.com
https://www.google.com
这是我们只想要上面的支持链接。如果我们输入像 www://abc 这样的垃圾数据,则不允许像这样的ABCDEFG。
我在Drupal中尝试过这样:
这是drupal自定义代码:
$form['web_url'] = array(
'#title' => 'Web URL :',
'#type' => 'textfield',
'#size' => 100,
'#default_value' => @$sourcepath,
'#required' => TRUE,
'#maxlength' => 100,
'#attributes' => array('class' => array('myclass_edit')),
);
function edit_files_form_validation($form, &$form_state){
$website_url = $form_state['values']['web_url'];
drupal_set_message("hi");
drupal_set_message($website_url);
if(!preg_match("/^(http[s]?)':'/'/([aZ09-_]*?'.)?([aZ09-_]{2,}'.)(['w'.]{2,5})$" ,$website_url )){
form_set_error('web_url',t('Please use only an valid URL links'));
}
}
但不是我的要求。
你可以试试这个正则表达式
/^((ht|f)tp(s?)':'/'/|~/|/)?([w]{2}(['w'-]+'.)+(['w]{2,5}))(:['d]{1,5})?/
http://www.google.com ,
https://www.google.com,
ftp://www.google.com,
www.google.com
功能>
function valid_url($value)
{
$pattern = "/^((ht|f)tp(s?)':'/'/|~/|/)?([w]{2}(['w'-]+'.)+(['w]{2,5}))(:['d]{1,5})?/";
if (!preg_match($pattern, $value))
{
return FALSE;
}
return TRUE;
}
你可以使用这个正则表达式
/^(http|https)?://[a-zA-Z0-9-.]+.[a-z]{2,4}/
这是我
的解决方案:
^(http[s]?)':'/'/([aZ09-_]*?'.)?([aZ09-_]{2,}'.)(['w'.]{2,5})$
获取协议、子域(如果存在)、域(必需)和分机(必需)。
规则:
需要 http 或 https
域必须包含少于 2 个字符
Ext 必须包含少于 2 个字符和 5 个字符的限制
例子:
http://tonton.google.fr
1. [0-4] `http`
2. [7-14] `tonton.`
3. [14-21] `google.`
4. [21-23] `fr`
http://www.google.co.uk
1. [46-50] `http`
2. [53-57] `www.`
3. [57-64] `google.`
4. [64-69] `co.uk`
https://paulrad.com
1. [70-75] `https`
3. [78-86] `paulrad.`
4. [86-89] `com`
演示:https://regex101.com/r/pV1hX8/2
^(?:(?:http|https):'/'/)?(?:['w-]+'.)+['w]+(?:'/['w- .'/?]*)?$
你可以试试这个。
$re = "/^(?:(?:http|https):''/''/)?(?:[''w-]+''.)+[''w]+(?:''/[''w- .''/?]*)?$/m";
$str = "http://google.com'nhttps://google.com";
preg_match_all($re, $str, $matches);