標籤:反向 regex 開頭 修飾符 格式 常用 bcd 判斷字串 分行符號
【定界符】
通常使用"/"做為定界符開始和結束,也可以使用"#"。一般在字串中有很多"/"字元的時候,使用"#"做定界符,因為正則的時候這種字元需要轉義,比如uri。
<?php /** * 定界符 * **/ $regex = ‘/^http:\/\/([\w.]+)\/([\w]+)\/([\w]+)\/([\w]+)\/([\w]+)\/([\w]+)\.html$/i‘; $str = ‘http://php1234.cn/a/functions/2016/0905/50.html‘; $matches = array(); if(preg_match($regex, $str, $matches)){ var_dump($matches); } $regex = ‘#^http:\/\/([\w.]+)\/([\w]+)\/([\w]+)\/([\w]+)\/([\w]+)\/([\w]+)\.html$#i‘; if(preg_match($regex, $str, $matches)){ var_dump($matches); }?>
輸出結果:array(7) { [0]=> string(47) "http://php1234.cn/a/functions/2016/0905/50.html" [1]=> string(10) "php1234.cn" [2]=> string(1) "a" [3]=> string(9) "functions" [4]=> string(4) "2016" [5]=> string(4) "0905" [6]=> string(2) "50"}array(7) { [0]=> string(47) "http://php1234.cn/a/functions/2016/0905/50.html" [1]=> string(10) "php1234.cn" [2]=> string(1) "a" [3]=> string(9) "functions" [4]=> string(4) "2016" [5]=> string(4) "0905" [6]=> string(2) "50"}
【修飾符】
用於改變Regex行為的符號,上例中的運算式最後面的/i就是一個修飾符,用來忽略大小寫,還有一個較常用的是"x",用來表示忽略空格的。
【字元域】
用方括弧擴起來的部分就是字元域,如上例中的:[\w]。
【限定符】
如[\w]{3,5}或者[\w]*或者[\w]+這些[\w]後面的符號都表示限定符。{3,5}表示3到5個字元。{3,}超過3個字元,{,5}最多5個。{3}三個字元。* 表示0到多個。+ 表示1到多個。
【脫字元】
^:放在字元域(如:[^\w])中表示否定(不包括的意思)即“反向選擇”。 放在運算式之前,表示以當前這個字元開始。(/^n/i,表示以n開頭)。注意:我們經常管"\"叫"跳脫字元"。用於轉義一些特殊符號,如".","/"
【萬用字元】
判斷字串中某些字元的存在與否!格式:正向預查:(?=) 相對應的 (?!)表示否定意思反向預查:(?<=) 相對應的 (?<!)表示否定意思
<?php /** * 萬用字元 * **/ $regex = ‘/(?<=c)d(?=e)/‘; /* d 前面緊跟c, d 後面緊跟e*/ $str = ‘abcdefgk‘; $matches = array(); if(preg_match($regex, $str, $matches)){ var_dump($matches); } $regex = ‘/(?<!c)d(?!e)/‘;//否定意義 $str = ‘abcdefgdk‘; if(preg_match($regex, $str, $matches)){ var_dump($matches); }?>
輸出結果:array(1) { [0]=> string(1) "d"}array(1) { [0]=> string(1) "d"}
【惰性匹配】
格式:限定符?原理:"?":如果前面有限定符,會使用最小的資料。如“*”會取0個,而“+”會取1個,如過是{3,5}會取3個。
<?php /** * 惰性匹配 * **/ $regex = ‘/heL*/i‘; $str = ‘heLLLLLLLLLLLLLLLL‘; if(preg_match($regex, $str, $matches)){ var_dump($matches); } $regex = ‘/heL*?/i‘; $str = ‘heLLLLLLLLLLLLLLLL‘; if(preg_match($regex, $str, $matches)){ var_dump($matches); } $regex = ‘/heL+?/i‘; $str = ‘heLLLLLLLLLLLLLLLL‘; if(preg_match($regex, $str, $matches)){ var_dump($matches); } $regex = ‘/heL{5,8}?/i‘; $str = ‘heLLLLLLLLLLLLLLLL‘; if(preg_match($regex, $str, $matches)){ var_dump($matches); }?>
輸出結果:array(1) { [0]=> string(18) "heLLLLLLLLLLLLLLLL"}array(1) { [0]=> string(2) "he"}array(1) { [0]=> string(3) "heL"}array(1) { [0]=> string(7) "heLLLLL"}
* :0到多次 +:1到多次還可以寫成{1,} ? :0或1次 . :匹配除分行符號外的所有單個的字元 \w: [a-zA-Z0-9_] \s:空白字元(空格,分行符號,斷行符號符)[\t\n\r] \d:[0-9]
PHPRegex概念