[精讚] [會員登入]
2146

[PHP] preg_match 的貪婪和不貪婪比對

在php preg_match中預設是採用貪婪比對,太貪婪反而不符合需要,因此得採用「非貪婪比對」...

分享此文連結 //n.sfs.tw/10433

分享連結 [PHP] preg_match 的貪婪和不貪婪比對@新精讚
(文章歡迎轉載,務必尊重版權註明連結來源)
2019-10-25 08:59:03 最後編修
2016-12-14 23:42:19 By 張○○
 

自動目錄

[PHP] preg_match 的貪婪和不貪婪比對 greedy/non-greedy match

在php preg_match中預設是採用貪婪比對,太貪婪反而不符合需要,因此得採用「非貪婪比對」,只要在modifier 中加上"U"即可,如下範例:

$str= "A running <b>dog</b> rams a walking <b>pig</b>.";
 
// Greedy matches ... default matches 貪婪比對,取出最大字串
$IsMatch= preg_match('/<b>(.*)<\/b>/', $str, $match);
if( $IsMatch ){
  print $match[1] . "\n" ;
}
 
// Nongreedy matches, use U modifier 非貪比對,取出最頭及最小字串
$IsMatch= preg_match('/<b>(.*)<\/b>/U', $str, $match);
if( $IsMatch ){
  print $match[1] . "\n" ;
}

執行結果:

dog</b> rams a walking <b>pig
dog

參考資料

[1] PHPcook http://docstore.mik.ua/orelly/webprog/pcook/ch13_05.htm

[2] Regex modifiers http://php.net/manual/en/reference.pcre.pattern.modifiers.php


原文 2013-09-25 01:11:01

END

你可能感興趣的文章

[PHP] 處理mail 函式的標題中文字亂碼 PHP的mail函式若標題有中文字得先處理過,否則收信者會看到亂碼

[PHP>7.3] switch中的 Did you mean to use "continue 2"? 除錯 這近更新 PHP到7.3版以後,出現這樣的錯:targeting switch is equivalent to "break". Did you mean to use "continue 2"?解決方法

[PHP] 移除陣列或字串中的重覆元素 移除陣列或字串中的重覆元素

PHP 移除陣列中的元素 要移除陣列中的其中一項元素

[CodeIgniter 3] COOKIE的使用 PHP CodeIgniter 3 中COOKIE的使用超簡單

[PHP] CodeIgniter 3+pure+smarty安裝及環境設置1/2 PHP framework CodeIgniter 3+ pure CSS +smarty Template Engine的整合

我有話要說

>>

限制:留言最高字數1000字。 限制:未登入訪客,每則留言間隔需超過10分鐘,每日最多5則留言。

訪客留言

[無留言]

隨機好文

UTF-8 BOM (Byte Order Mark) 的問題 在 Michael Kaplan 那看到 Every character has a story #4: U+feff

安裝SPHINX支援中文 新版本的 sphinx 和舊版不同,網路上很多範例和教學是不能用的。此文是安裝和設定方法分享

[札記] 2016.7~12月札記 札記,只是札記

[PHP] 檢查IP是否在某個網段內 mtachcidr 要檢查IP是否在某個網段內,要寫幾行?10行?5行? 不用,只要2行。以下是我寫的 code /** * matchCI

[Mysql] 資料型態int, float, double, text, char, varchar, blob大小 Mysql中資料型態int, float, text, char, varchar, blob大小