[精讚] [會員登入]
2483

[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] codeignitor4+ smarty4 這篇整合 php 的framework codeignitor4 + smarty4。

PHP程式經驗 #1 -- 靜態的物件比動態物件快 驗證 1. 使用動態物件函式 > 使用靜態物件函式。 2. 使用有宣告的靜態物件函式 > 使用動態無宣告的靜

[CodeIgniter3] CI3 Session 失敗的問題 這次把我的程式放到Centos8,結果sesssion 一直沒作用,真的不知道發生了什麼事?

[PHP] 讀取作業系統程式執行結果 PHP讀取作業系統程式執行結果

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

[PHP] 字串編碼及解碼函式 為何要將字串編碼?理由很簡單,就是不要讓人家輕易的知道字串內容是什麼。例如點選分頁時,我們常會用這樣的連結: index

隨機好文

[jQuery] select 元件的取值及給值 html中的元件select,在jquery中要如何使用?

[Freebsd] 使用 ADSL 撥接上網 Freebsd上要使用 ADSL 撥接上網,該如何設定?

PHP for sphinx 函式庫安裝 PECL/sphinx PHP>= 5.2.2 已經能原生支援 sphinx,可是預設的沒有裝,我們得自己裝才能用

[Win7] 燒錄 iso 檔 在Windows7 中內建燒錄程式,可以直接把檔案拉到光碟機裡,再執行燒錄。

[CodeIgniter3] 解決無法上傳特定檔案(.sb2)的問題 上傳時出現The filetype you are attempting to upload is not allowed,要怎麼解決?