php语言 百分网手机站

PHP常用正则表达式

时间:2020-09-15 19:09:04 php语言 我要投稿

PHP常用正则表达式

  header("Content-Type:text/html;charset=utf-8"),这一句一般都是用于设置页面的字符集,防止出现乱码,虽然跟本节没多大关系,但也可以当作基础知识。

  //匹配英文域名网址:http,https。域名中没有下划线,后缀为字母

  1

  2

  3

  $preg = '/^(https?://)?([a-zd.-]+).([a-z]+)$/i';

  $str = 'www.liqingbo.cn';

  echo preg_match($preg, $str);

  //匹配url

  1

  2

  3

  $preg = '/^([a-z]+)://([^s]*)/i';

  $str = 'http://blog.liqingbo.cn';

  echo preg_match($preg, $str);

  //匹配IP地址

  1

  2

  3

  $preg = '/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/';

  $str = '255.255.255.250';

  echo preg_match($preg, $str);

  //匹配一个html标签

  1

  2

  3

  4

  $preg = '/^<([a-z]+)([^<]+)*(?:>(.*)</1>|s+/>)$/';

  $str = '<a href="http://www.icaigen.com">菜根网</a>';

  $res = preg_match_all($preg, $str, $matches);

  var_dump($matches);

  //从一段html中提取一张图片

  1

  2

  3

  4

  5

  $preg = '/<img[^>]+(src="([^"<>']+)"|src='([^"<>']+)')[^<>]*>/';

  $html = '<div><a href="http://baidu.com"><img src="http://baidu.com/src/img0.gif" /><img src="http://baidu.com/src/img1.gif" /></a></div>';

  $res = preg_match_all($preg, $html, $matches, PREG_PATTERN_ORDER);

  //var_dump($matches);

  echo $matches[2][0]; //src

  //匹配电子邮箱

  1

  2

  3

  $preg = '/^([a-z0-9_.-]+)@([a-z0-9.-]+).([a-z]+)$/i';

  $str = 'jeddy_liu-jin@gmail.com';

  echo preg_match($preg, $str);

  //匹配密码

  1

  2

  3

  $preg = '/^[a-z0-9@_.-]{6,18}$/';

  $str = 'liujin@1234.com';

  echo preg_match($preg, $str);

  //匹配用户名

  1

  2

  3

  $preg = '/^[a-z0-9_-]{3,16}$/';

  $str = 'liujin-88';

  echo preg_match($preg, $str);

  //国内座机

  1

  2

  3

  $preg = '/^(0d{2,3})-?(d{7,8})$/';

  $str = '015-5415488';

  echo preg_match($preg, $str);

  //国内手机

  1

  2

  3

  $preg = '/^1[3|4|5|8]d{9}$/';

  $str = '18012345678';

  echo preg_match($preg, $str);

  //匹配邮编

  1

  2

  3

  $preg = '/^[1-9]d{5}$/';

  $str = '415000';

  echo preg_match($preg, $str);

  //匹配身份证号

  1

  2

  3

  $preg = '/(^d{15}$)|(^d{18}$)/';

  $str = '430701198806520';

  echo preg_match($preg, $str);

  //匹配汉字

  1

  2

  3

  4

  $preg = '/^[x{4e00}-x{9fa5}]+$/u';

  $str = 'PHP博客';

  preg_match($preg, $str, $match);

  var_dump($match);


【PHP常用正则表达式】相关文章:

PHP常用的正则表达式09-21

PHP常用单词09-30

PHP常用开发技巧10-15

PHP常用代码大全10-02

PHP常用函数汇总08-27

PHP面试常用知识08-21

PHP常用函数总结06-20

PHP正则匹配中文字母数字正则表达式09-04

PHP常用魔术方法讲解10-01