[精讚] [會員登入]
2485

[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 cli 傳入參數 php cli (PHP命令列的傳入參數使用方法

[PHP] codeignitor4+ smarty4 這篇整合 php 的framework codeignitor4 + smarty4。

[PHP+ci4] codeignitor4+ smarty5 這篇整合 php 的framework codeignitor4 + smarty5。

[PHP] 取得檔名和路徑:basename, dirname 由絕對路徑取的路徑及檔名的方法

[PHP] 使用FTP PHP 上使用 FTP 的寫法

[PHP] 判斷文字、數字、文字加數字的方法 幾個PHP數字和文字操作上的小眉角:判斷文字、數字、文字加數字的方法

隨機好文

[jQuery] 利用load()來達成ajax的寫法 jQuery中利用load()來達成ajax的寫法,也有人稱他是假的ajax,作法就是..

[jQuery] textarea 的取值和給值 HTML 的 TEXTAREA 標籤若要用 jquery 取值,不能使用 .text() 或 .html() ,使用 .

NETCRAFT發現你的網站及作業系統 NETCRAFT可以發現你的網站及作業系統

世紀帝國征服者新版本--被遺忘的帝國 世紀帝國征服者新版本--被遺忘的帝國 世紀二代的征服者是精典遊戲中的精典,aofe更好玩...

[Wildfly10] 發佈war檔 deploy war file onto wildfly10