实用的PHP正则表达式

2025-04-22 16:26:21

1、1. 验证E-mail地址这是一个用于验证电子邮件的正则表达式。但它并不是高效、完美的解决方案。在此不推荐使用查看源代码打印帮助$email="test刺胳挤萧@ansoncheung.tk";if(preg_match('/^[^0-9][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[@][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[.][a-zA-Z]{2,4}$/',$email)) {echo"Your email is ok.";}else{echo"Wrong email address format";}

2、2. 验证用户名这是一个用于验证用户名的实例,其中包括字母、数字(A-Z,a-z,0-9)、下划线以及最低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、3. 验证电话号码这是一个验证中国电话号码的实例。查看源代码打印帮助$phone="(021)423-2323";if(preg_match('/\(?\d{3}\)?[-\s.]?\d{3}[-\s.]\d{4}/x',$phone)) {echo"Is ok.";}else{echo"Wrong.";}

4、4. 验证IP地址这是一个用来验证IPv4地址的实例。查看源代码打印帮助$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.";}

5、5. 验证邮政编码这是一个用来验证邮政编码的实例。$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.";}

6、6. 验证域名查看源代码打印帮助$url="http://anepx.com/";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.";}

7、7. 从特定URL中提取域名查看源代码打印帮助$url="http://blog.anepx.com/?cat=7";preg_match('@^(?:http://)?([^/]+)@i',$url,$matches);$host=$matches[1];echo$host;

8、8. 将文中关键词高亮显示查看源代码打印帮助$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;

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
相关推荐
  • 阅读量:47
  • 阅读量:85
  • 阅读量:68
  • 阅读量:24
  • 阅读量:32
  • 猜你喜欢