PHP 常用的正则表达式例子
<?php header("Content-Type:text/html;charset=utf-8"); //匹配英文域名网址:http,https。域名中没有下划线,后缀为字母 $preg = '/^(https?:\/\/)?([a-z\d\.-]+)\.([a-z]+)$/i'; $str = 'www.onestopweb.cn'; echo preg_match($preg, $str); //匹配url $preg = '/^([a-z]+):\/\/([^\s]*)/i'; $str = 'http://blog.liqingbo.cn'; echo preg_match($preg, $str); //匹配IP地址 $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标签 $preg = '/^<([a-z]+)([^<]+)*(?:>(.*)<\/\1>|\s+\/>)$/'; $str = '<a href="http://www.onestopweb.cn">一站式</a>'; $res = preg_match_all($preg, $str, $matches); print_r($matches); //从一段html中提取一张图片 $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 //匹配电子邮箱 $preg = '/^([a-z0-9_\.-]+)@([a-z0-9\.-]+)\.([a-z]+)$/i'; $str = '[email protected]'; echo preg_match($preg, $str); //匹配密码 $preg = '/^[a-z0-9@_\.-]{6,18}$/'; $str = '[email protected]'; echo preg_match($preg, $str); //匹配用户名 $preg = '/^[a-z0-9_-]{3,16}$/'; $str = 'liujin-88'; echo preg_match($preg, $str); //国内座机 $preg = '/^(0\d{2,3})-?(\d{7,8})$/'; $str = '020-5415488'; echo preg_match($preg, $str); //国内手机 $preg = '/^1[3|4|5|8]\d{9}$/'; $str = '18012345678'; echo preg_match($preg, $str); //匹配邮编 $preg = '/^[1-9]\d{5}$/'; $str = '415000'; echo preg_match($preg, $str); //匹配身份证号 $preg = '/(^\d{15}$)|(^\d{18}$)/'; $str = '430701198806520'; echo preg_match($preg, $str); //匹配汉字 $preg = '/^[\x{4e00}-\x{9fa5}]+$/u'; $str = '阅谁问君诵'; echo preg_match($preg, $str); ?>
效果图:
相关推荐
wangzhaotongalex 2020-10-20
wyq 2020-11-11
TLROJE 2020-10-26
风雨断肠人 2020-10-13
duanqingfeng 2020-09-29
rechanel 2020-11-16
cshanzhizi 2020-10-16
luofuIT成长记录 2020-09-22
phphub 2020-09-10
taomengxing 2020-09-07
MaggieRose 2020-08-19
flyingssky 2020-08-18
山水沐光 2020-08-18
jyj00 2020-08-15
AHuqihua 2020-08-09
山水沐光 2020-08-03