在我們上篇文章中我們帶大家瞭解了phpRegex的入門,那麼既然學習完入門,那我們就要開始學習phpRegex的使用了,那麼下面就具體在PHP中怎麼運用吧,本文通過具體的執行個體,給大家講解了PHP中Regex的使用方法。
這篇文章的寫作方式不是講理論,而是通過具體的例子來瞭解正則,這樣也更有實踐性,在此基礎上再去看Regex的基本概念會更有收穫。
禁止分組的捕獲
在正則中分組很有用,可以定義子模式,然後可以通過後向引用來引用分組的內容,但是有的時候僅僅想通過分組來進行範圍定義,而不想被分組來捕獲,通過一個例子就能明白:
$str = "http://www.google.com";$preg= "/http:\/\/\w+\.\w+.(?:net|com|cn)+/is";$preg2= "/http:\/\/\w+\.\w+.(net|com|cn)+/is";preg_match($preg,$str,$arr);preg_match($preg2,$str,$arr2);
當模式中出現?:表示這個括弧的分組不會被引用,運行下例子就能明白。
preg_match() 和 preg_match_all() 的區別
preg_match() 在匹配模式的時候匹配到一次就結束,而 preg_match_all() 則進行全域匹配,通過一個例子就能明白:
$str='hello world china';$preg="/\w+\s/is";preg_match($preg,$str,$arr);print_r($arr);preg_match_all($preg,$str,$arr);print_r($arr);
正確理解 $ 和 ^
先說一個正則,為了匹配是否是手機號:
$str = "13521899942a";$preg="/1[\d]{3,15}/is";if (preg_match($preg,$str,$arr)) { echo "ok";}
雖然字串中有一個英文字母,但是這個子模式卻匹配了,原因就在於模式比對到後就結束了,不會再去尋找英文字母,為瞭解決這問題 $ 和 ^ 就發揮作用了,比如讓字串的開始和結尾必須匹配一定的模式,修改如下:
$str = "13521899942a";$preg="/1[\d]{3,15}$/is";if (preg_match($preg,$str,$arr)) { echo "ok";}
$ 和 ^ 的跨行模式
預設的情況下,$ 和 ^ 只會匹配完整段落的開始和結尾,但是通過改變選項,允許匹配文本的每一行的開始和結尾,通過下面的例子就能明白
$str='helloworld';$preg='/\w+$/ism';//$preg='/(?m)\w+$/is';preg_match_all($preg,$str,$arr);print_r($arr);
分組命名
在正則中通過括弧分組後,可以使用 \1,\2 這樣的數字進行後向引用,但是假如正則中模式太多,在使用的時候就會比較混亂,這時候可以採用分組命名來進行引用,看個例子:
$str ="email:ywdblog@gmail.com;";preg_match("/email:(?<email>\w+?)/is", $str, $matches);echo $matches["email"] . "_" . $matches['no'];
懶惰模式
正則在匹配的時候是貪婪的,只要符合模式就會一直匹配下去,下面的例子,匹配到的文本是 <h2>hello</h2><h2>world</h2>
$str = "<h2>hello</h2><h2>world</h2>";$preg = "/<h2>.*<\/h2>/is";preg_match($preg,$str,$arr);print_r($arr);
通過改變一個選項可以修改為懶惰模式,就是一旦匹配到就中止,修改代碼如下:
$str = "<h2>hello</h2><h2>world</h2>";$preg = "/<h2>.*?<\/h2>/is";preg_match($preg,$str,$arr);print_r($arr);
進一步理解 preg_match_all()
通過這函數的最後一個參數,能夠返回不同形式的數組:
$str= 'jiangsu (nanjing) nantongguangdong (guangzhou) zhuhaibeijing (tongzhou) haidian';$preg = '/^\s*+([^(]+?)\s\(([^)]+)\)\s+(.*)$/m';preg_match_all($preg,$str,$arr,PREG_PATTERN_ORDER);print_r($arr);preg_match_all($preg,$str,$arr,PREG_SET_ORDER);print_r($arr);
強大的正則替換回調
雖然 preg_replace() 函數能完成大多數的替換,但是假如你想更好的控制,可以使用回調,不用多說看例子:
$str = "china hello world";$preg = '/\b(\w+)(\w)\b/';function fun($m){ return $m[1].strtoupper($m[2]);}echo preg_replace_callback($preg,"fun",$str);
在這一點上,PHP 比 Python 強大的多,Python 中沒有正則回調,不過可以使用閉包的方式解決,可看我以前的文章。
preg_quote()
這個函數類似於 Python 中的 re.compile() 函數,假如在模式中一些元字元僅僅想表達字元的本身含義,可以轉義,但是假如在模式中寫太多的轉義,會顯得很混亂,可以使用這個函數來統一轉義:
$str = '\\*china*world';$preg = "\*china";$preg = preg_quote($preg);echo $preg;preg_match( "/{$preg}/is",$str,$arr);print_r($arr);
向前尋找 ?= 的妙用
用英文解釋可能比較貼切:
The "?=" combination means "the next text must be like this". This construct doesn't capture the text.
(1)這個例子可以擷取 URL 中的協議部分,比如 https,ftp,注意 ?: 後面的部分不在返回的內容中。
$str = "http://www.google.com";$str = "https://www.google.com";$preg = '/[a-z]+(?=:)/';preg_match($preg,$str,$arr);print_r($arr);
(2)"invisible" 分隔字元
也叫 “zero-width” 分隔字元,參考下面的例子:
$str = ("chinaWorldHello");$preg = "/(?=[A-Z])/";$arr = preg_split($preg,$str);print_r($arr);
(3)匹配強密碼
instead of specifying the order that things should appear, it's saying that it must appear but we're not worried about the order.
The first grouping is (?=.{8,}). This checks if there are at least 8 characters in the string. The next grouping (?=.[0-9]) means "any alphanumeric character can happen zero or more times, then any digit can happen". So this checks if there is at least one number in the string. But since the string isn't captured, that one digit can appear anywhere in the string. The next groupings (?=.[a-z]) and (?=.[A-Z]) are looking for the lower case and upper case letter accordingly anywhere in the string.
$str= "HelloWorld2016";if (preg_match("/^.*(?=.{8,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).*$/", $str,$arr)){ print_r($arr);}
向後尋找 ?<=
?<= 表示假如匹配到特定字元,則返回該字元後面的內容。
?= 表示假如匹配到特定字元,則返回該字元前面的內容。
$str = 'chinadhello';$preg = '/(?<=a)d(?=h)/'; preg_match($preg, $str, $arr);print_r($arr);
總結:
在文章我們主要給大家介紹了phpRegex在某種模式下的運用,以及簡單介紹了phpRegex中的一些函數,希望對你有所協助!
相關推薦;
phpRegex入門詳解
PHPRegex之文法詳解
phpRegex應用
phpRegex