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 = '<p><a href="http://baidu.com"><img src="https://pic.66455.cn/800dx/20210819/error.html /><img src="https://pic.66455.cn/800dx/20210819/error.html /></a></p>';
$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 = '/^0d2,3-?d7,8$/';
$str = '015-5415488';
echo preg_match$preg, $str;
//国内手机
1
2
3
$preg = '/^1[3|4|5|8]d9$/';
$str = '18012345678';
echo preg_match$preg, $str;
//匹配邮编
1
2
3
$preg = '/^[1-9]d5$/';
$str = '415000';
echo preg_match$preg, $str;
//匹配身份证号
1
2
3
$preg = '/^d15$|^d18$/';
$str = '430701198806520';
echo preg_match$preg, $str;
//匹配汉字
1
2
3
4
$preg = '/^[x4e00-x9fa5]+$/u';
$str = 'PHP博客';
preg_match$preg, $str, $match;
var_dump$match;