作者:3#对于一个专注于web技术的80后来说,你不需要和聪明人斗,只需要和那些懒惰的人斗,你一定会超越大部分人!思否@吉客小俊官方第一篇原创企业博客:?极客君?B站地址:?哔哩哔哩?继续从上一节讲正则..模式修饰符或模式单元语法:/atom+元字符+量词/模式修正符号或/正则表达式/模式修饰符在PHP中也称为修饰符,包括:i,m,s,你,e。模式修饰符必须与常规函数一起使用才有意义。例如:"//iU"1.模式修饰符是几个字母。2.可以一次用一个,每个都有一定的意义,也可以连续使用多个。3.用于调整整个正则表达式,也可以说是正则表达式功能的扩展例如:“/abc/”只能匹配小写字母abc“/abc/i”可以匹配ABCabcAbcABcabcincase-insensitive如下:i:表示与pattern的匹配不区分大小写m:把字符串当成多行后,任意行可以任意开始或结束^和$s:对待字符串作为单行。如果不使用此模式修饰符,则“.”在元字符中默认是不能匹配换行符的,也就是说,如果把一个字符串看成是单行,那么换行符只是一个普通的符号,并不代表换行符,所以.也可以匹配换行符![这里的字符串是双引号]x:表示忽略pattern中的空格,又是在常规pattern中字符串中没有空格!e:必须在preg_replace函数中使用正则表达式来替换字符串[现已弃用]A:必须以任何内容开头,一般使用^[理解]Z:必须以任何结尾,一般使用$[理解]D:它必须以某些内容结尾,但结束字符串之后不能有任何内容!m修饰符设置后就失效了!U:修正正则贪心模式原因:正则表达式的特点:就是比较“贪心”。一种是使用?Complete.*?.+?注意:如果两种方式同时出现贪婪模式将再次开启。例如,有.*?/U提示:并非所有语言都支持模式修饰符!==模式修饰符case==如下:$pattern='/abC/i';$string='abcABC';$pattern='/^w.+/im';$string='abcABCccccworldelement有什么错?';$pattern='/^w.+/ims';$string='abcABCccccworldelement怎么了?';$pattern='/thisisphp/ix';$string='thisisphp';$pattern='/this\s?is\s?php/i';$string='这是php';$pattern='/这是/AD';$string='这是php';$pattern='/^t.*/U';$string='这是php';$pattern='/^t.*?/U';$string='这是php';preg_match($pattern,$string,$arr);show($arr);接下来,让我们做一些非常简单的常规练习吧!练习一:匹配的用户名必须是英文+数字最多8位,最少5位如下:$string='wang12345';$pattern='/^[a-zA-Z0-9]{1}[a-zA-Z0-9]{4,7}/';preg_match($pattern,$string,$arr);show($arr);练习2:匹配Email如下:$string='1562hejun466@qq.com';//$string='mousesportsjonas@163.com';//$string='mouses.ports.jonas@163.com';//$string='mousical@public.net';//$string='mousical@public';$pattern='/^(?:\w+\.)?(?:\w+\.)?\w+@[a-zA-Z0-9]+(?:\.(?:net|org|com))?$/';preg_match($pattern,$string,$arr);笑w($arr);练习3:匹配HTTPURL的正则表达式如下:/**MatchURL例如:*http://www.baidu.com*http://baidu.com*baidu.com*知道.baidu.com等*/$string='http://www.baidu.com';$string='https://baidu.com';$string='https://www.baidu.com';$string='baidu.com';$string='zhidao.baidu.com';$string='http://zhidao.baidu.com';$pattern='/^(?:http[s]?:\/\/(?:www\.)?)?(?:[a-zA-Z0-9]+\.)?[a-zA-Z0-9]+\.(?:com|net|org)$/';preg_match($pattern,$string,$arr);show($arr);练习四:匹配手机号和座机号正则表达式如下:$string='63839154';$string='023-63505008';$string='18723188548';$string='0371-60333332';$pattern='/^1[35678]{1}\d{9}|0[0-9]{2,3}\-\d{7,8}|\d{7,8}/';preg_match($pattern,$string,$arr);显示($arr);所有图片爬取如下:$string=file_get_contents('http://www.mtime.com/');$pattern='/
/';preg_match_all($pattern,$string,$arrList);$patternReplace='/(?<=data-src=\").+?(?=\")/';foreach($arrList[0]as$k=>$v){preg_match($patternReplace,$v,$arr);如果(!空($arr[0])){$url[]=$arr[0];$patternList[]='/(?<=src=\").+?(?=\")/';echopreg_replace($patternList,$url,$arrList[0][$k]).'
';}}Exercise6:Match取出一个listpage中的所有titlenames并循环到一个table中//Exercise6:Match取出一个listpage中的所有titlenames并循环成一个form$string=file_get_contents('http://www.cqepc.cn/');$pattern='/\.+?\<\/div\>/s';preg_match_all($pattern,$string,$arr);echo'重庆航天职业学院招生就业信息';echo'';foreach($arr[0]as$k=>$v){echo'';echo''.$v.'';echo'
';}echo'';如果我的博客对你有帮助,请喜欢我的博客内容好吗?“喜欢”、“评论”、“收藏”?您的支持是我前进的动力。