[精讚] [會員登入]
2328

[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 數字加解密函式 自寫的數字加解密,勉強用

[PHP] 將字串的部分加上遮罩的函式 有些資料會想要隱藏部分的字元,例如身分證號或信用卡號、電話等。我寫了一個函式來完成這個功能。

[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] preg_match 的貪婪和不貪婪比對 在php preg_match中預設是採用貪婪比對,太貪婪反而不符合需要,因此得採用「非貪婪比對」...

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

[PHP8] 使用autoload autoload+ namespace +use 到了php7之後,namespace和use越來越重要,此篇整理autoload和namespace、use的結合使用。

我有話要說

>>

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

訪客留言

[無留言]

隨機好文

SELinux 常用指令和檔案 在Redhat系列中,Centos5以後加入了selinux,他並沒有這麼可怕,不必每次看到Selinux ,就想把他

看懂DSUB DVI HDMI USB等各式影音接頭 看懂DSUB DVI HDMI等各式影音接頭

TFTP Server 安裝及使用 讓設備的網路設定檔或是韌體經由TFTP拷備出來,操作的方法

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

[AS3] FLASH 引入外部as檔 FLASH AS3中,若要引用另外撰寫的 class(*.as) 檔案,該如何處理?