PHP常用正则表达式

来源:文书网 2.88W

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

PHP常用正则表达式

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

1

2

3

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

$str = '';

echo preg_match($preg, $str);

  //匹配url

1

2

3

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

$str = '';

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 = '';

echo preg_match($preg, $str);

 //匹配一个html标签

1

2

3

4

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

$str = '<a href="">菜根网</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=""><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_';

echo preg_match($preg, $str);

  //匹配密码

1

2

3

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

$str = &#';

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);

热门标签