PHP正则表达式(常用的7个例子)
来源:互联网 发布:怎样给淘宝客服发图片 编辑:程序博客网 时间:2024/05/15 13:43
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", '<span style="background:#5fc9f6">\1</span>', $text);echo $text;
0 0
- PHP正则表达式(常用的7个例子)
- php curl常用的5个例子
- php curl常用的5个例子
- php curl常用的5个例子
- php curl常用的5个例子
- php curl常用的5个例子
- PHP的curl常用的5个例子
- (实用篇)PHP curl常用的5个例子
- PHP常用的正则表达式
- 常用的PHP正则表达式
- php常用的正则表达式
- PHP常用的正则表达式
- PHP常用的正则表达式
- PHP常用的正则表达式
- php 常用的正则表达式
- PHP常用的正则表达式
- PHP常用的正则表达式
- PHP常用的正则表达式
- 面试题
- 算法--排序算法的介绍与总结(四)
- Linux守护进程
- C - Spanning Tree 最小生成树 Kruskal (第四届华中区程序设计邀请赛暨武汉大学第十三届校赛)
- #笔记#圣思园 JavaSE 第39讲——ArrayList源代码剖析
- PHP正则表达式(常用的7个例子)
- 使用gradle来构建Spring boot时遇到的问题
- 习题2-14
- Xcode6.2版本详解
- WEB开发文档2 总结
- Jmeter性能测试 入门
- 用C++流成员函数put输出单个字符
- Handler,message,Looper源码解析
- hash与map的区别联系应用