首页 > 后端开发 > php教程 > PHP正则表达式(常用的7个例子)_PHP教程

PHP正则表达式(常用的7个例子)_PHP教程

WBOY
发布: 2016-07-13 09:56:25
原创
869 人浏览过

PHP正则表达式(常用的7个例子)

1、验证E-mail

用filer_var 比用正则匹配更加好

 

if (filter_var('test+email@ansoncheung', FILTER_VALIDATE_EMAIL)) {
    echo "Your email is ok.";
} else {
    echo "Wrong email address format.";
}
登录后复制

2、验证用户名(验证用户名5-20之间)

$username = "user_name12";
if (preg_match('/^[a-z\d_]{5,20}$/i', $username)) {
    echo "Your username is ok.";
} else {
    echo "Wrong username format.";
}
登录后复制

3、验证ip地址

$IP = "198.168.1.78";
if (preg_match('/^(([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]).){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/',$IP)) {
    echo "Your IP address is ok.";
} else {
    echo "Wrong IP address.";
}
登录后复制

4、验证邮编

$zipcode = "12345-5434";
 if (preg_match("/^([0-9]{5})(-[0-9]{4})?$/i",$zipcode)) {
 echo "Your Zip code is ok.";
 } else {
 echo "Wrong Zip code.";
 }
登录后复制

5、验证域名

$url = "http://ansoncheung.tk/";
 if (preg_match('/^(http|https|ftp):\/\/([A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?/i', $url)) {
 echo "Your url is ok.";
 } else {
 echo "Wrong url.";
 }
登录后复制

6、从特定URL中提取域名

$url = "http://ansoncheung.tk/articles";
 preg_match('@^(?:http://)?([^/]+)@i', $url, $matches);
 $host = $matches[1];
echo $host;
登录后复制

7、文本中关键字高亮显示

$text = "Sample sentence from AnsonCheung.tk, regular expression has become popular in web programming. Now we learn regex. According to wikipedia, Regular expressions (abbreviated as regex or regexp, with plural forms regexes, regexps, or regexen) are written in a formal language that can be interpreted by a regular expression processor";
$text = preg_replace("/\b(regex)\b/i", &#39;<span style="background:#5fc9f6">\1</span>&#39;, $text);
echo $text;
登录后复制


 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/987986.htmlTechArticlePHP正则表达式(常用的7个例子) 1、验证E-mail 用filer_var 比用正则匹配更加好 if (filter_var(test+email@ansoncheung, FILTER_VALIDATE_EMAIL)) { echo Your email i...
相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板