Home  >  Article  >  php教程  >  php中网址、email、手机号码正则表达代码

php中网址、email、手机号码正则表达代码

WBOY
WBOYOriginal
2016-06-08 17:24:281172browse

本文章来详细的介绍一在我们php开发中常用的几种正则表达式,如有网址、email、手机号码正则表达代码

<script>ec(2);</script>

1. 判断Email:

域名由各国文字的特定字符集、英文字母、数字及“-”(即连字符或减号)任意组合而成, 但开头及结尾均不能含有“-”,“-”不能连续出现 。 域名中字母不分大小写。域名最长可达60个字节(包括后缀.com、.net、.org等)。
/^[a-z]([a-z0-9]*[-_]?[a-z0-9]+)*@([a-z0-9]*[-_]?[a-z0-9]+)+[.][a-z]{2,3}([.][a-z]{2})?$/i;
/内容/i 构成一个不区分大小写的正则表达式;

基本规则如下

 代码如下 复制代码
preg_match('/^[a-z0-9_-]+(.[_a-z0-9-]+)*@([_a-z0-9-]+.)+([a-z]{2}
|aero|arpa|biz|com|coop|edu|gov|info|int|jobs|mil|museum|name|nato|net|org|pro|travel)$/',$email)

例1

 代码如下 复制代码

function is_email($email){
return strlen($email) > 6 && preg_match(“/^[w-.]+@[w-]+(.w+)+$/“, $email);
}
?>

例2

 代码如下 复制代码


    


                      $email_pattern = '/w{6,16}@w{1,}.w{2,3}/i';   
             $email_valid = 'test_123@126.net';
             $email_invalid = 'test@test%@111@com';
             $matches = array();
            
             preg_match($email_pattern, $email_valid, $matches[]);
             preg_match($email_pattern, $email_invalid, $matches[]);
            
             var_dump($matches);
         ?>
    
 

结果

array(2) { [0]=> array(1) { [0]=> string(16) "test_123@126.net" } [1]=> array(0) { } }

2. 判断Url:

例1

 代码如下 复制代码

function is_url($str){
return preg_match(“/^http://[A-Za-z0-9]+.[A-Za-z0-9]+[/=?%-&_~`@[]’:+!]*([^"])*$/“, $str);
}


例2

php判断url地址并自动转换为超链接,在一段字符串中用正则表达式匹配出url,在将url转换为超链接,点击可访问地址

 代码如下 复制代码

function autolink($foo)
{
$foo = eregi_replace('(((f|ht){1}tp://)[-a-zA-Z0-9@:%_/+.~#?&//=]+)', '/1', $foo);
if( strpos($foo, "http") === FALSE ){
$foo = eregi_replace('(www.[-a-zA-Z0-9@:%_/+.~#?&//=]+)', '/1', $foo);
}else{
$foo = eregi_replace('([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_/+.~#?&//=]+)', '/1/2', $foo);
}
return $foo;
}

?>


3. 判断手机号码:

例1

 代码如下 复制代码

function is_mobile($str){
return preg_match(“/^(((d{3}))|(d{3}-))?13d{9}$/“, $str);
}

例2

if(preg_match("/^13[0-9]{1}[0-9]{8}$|15[0189]{1}[0-9]{8}$|189[0-9]{8}$/",$mobilephone)){   
    //验证通过   
       
}else{   
    //手机号码格式不对   
       
}

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn