- ^ 和 & 通配符
^表示 必须匹配到字符串的开头;&必须匹配到字符串的结尾preg_match("/^cow/","Dave was a cowand"); //return false preg_match("/^cow/","cowabunga"); //return true preg_match("/cow$/","Dave was a cowhand"); //return false preg_match("/cow$/","Don't have a cow"); //return false
句点( . ) 可以匹配任意单个字符
反斜杠/ 用来 对特殊字符进行转义preg_match("/c.t/","cat"); //return true preg_match("/c.t/","cut"); //return true
preg_match("/\$5\.00","your bill is $5.00 exactly"); //return true
字符类
使用方括号 [] 可以建立一个自定义的字符接受类
可以用 ^ 来否定这个字符类
可以用 - 定义一个字符的范围 e,g. [0-9] 表数字,[a-zA-Z] 表所有字母preg_match("/c[aeiou]t/","I cut my hand"); //匹配 字符以c开头,t结尾,中间为元音字母 preg_match("/c[^aeiou]t/");
选择性
| 分隔符 用来表示可选择性preg_match("/cat|dog/","the cat rubbed my legs"); //return true
- 重复序列
利用量词来控制字符的重复
? 0次或1次
* 0次或多次
+ 1次或多次
{n} 出现n次
{n,m} 最小n次,不超过m次
{n ,} 最少n次preg_match("/ca+t/","caaaaaat"); //return true
匹配行为
匹配到的数组的第0个元素 被设置为匹配的整个字符串,第1个元素为子模式匹配到的子字符串,第二个元素为第二个子模式。。。以此类推
注:书中还提到了 字符类 和 锚 的更详细内容 等用到时再查看PHP开发文档 此笔记只记录一些常用的基础知识preg_match("/is (.*)$","the key is in my pants",$captured); //$captyred[1]的值是 'in my pants'
- 非贪婪模式
正则表达式的匹配都是基于贪婪的 即最大匹配
非贪婪模式 只需要在量词后面加个 ? 即可实现尽可能少的匹配preg_match("/(<.*>)/","do <b>not</b> press the button", $match); //$match[1] = '<b>not</b>' preg_match("/(<.*?>)/","do <b>not</b> press the button", $match); //$match[1] = '<b>'