--------------------------------------------------------------------------------
Perl 相容語法函式庫
--------------------------------------------------------------------------------
本函式庫共有 4 個函式
對熟悉 Perl 的 Webmaster 來說,使用這個函式庫可以將 Prel 語言中最強的樣式比對功能帶到 PHP 之中。更多的細節可以參考 Programming Perl 這本書第二章中有關樣式比對 (Pattern Matching) 的部份 (中譯本為 Perl 程式設計,第 63 頁起)
preg_match: 字串比對剖析。
preg_match_all: 字串整體比對剖析。
preg_replace: 字串比對剖析並取代。
preg_split: 將字串依指定的規則切開。
--------------------------------------------------------------------------------
函式:preg_match()
--------------------------------------------------------------------------------
Perl 相容語法函式庫
preg_match
字串比對剖析。
語法: int preg_match(string pattern, string subject, array [matches]);
傳回值: 整數/陣列
函式種類: 資料處理
內容說明
本函式以 pattern 的規則來剖析比對字串 subject。比對結果傳回的值放在陣列參數 matches 之中,matches[0] 內容就是原字串 subject、matches[1] 為第一個合乎規則的字串、matches[2] 就是第二個合乎規則的字串,余類推。若省略參數 matches,則只是單純地比對,找到則傳回值為 true。
--------------------------------------------------------------------------------
函式:preg_match_all()
--------------------------------------------------------------------------------
Perl 相容語法函式庫
preg_match_all
字串整體比對剖析。
語法: int preg_match_all(string pattern, string subject, array matches, int [order]);
傳回值: 整數
函式種類: 資料處理
內容說明
本函式以 pattern 的規則來整體剖析比對字串 subject。比對結果傳回的值放在陣列參數 matches 之中,並依順序值 order 排序。參數 order 的值有 PREG_PATTERN_ORDER 及 PREG_SET_ORDER 二種。若沒有 order 值,則系統自動以 PREG_PATTERN_ORDER 代入 order 值中。傳回值為合乎比對結果的數目,若沒有或錯誤則傳回 false 值。
使用范例
PREG_PATTERN_ORDER 的例子
preg_match_all("|<[^>]+>(.*)[^>]+>|U", "a test ", $out, PREG_PATTERN_ORDER);
print $out[0][0].", ".$out[0][1]."\n";
print $out[1][0].", ".$out[1][1]."\n"
?>
傳回值為
example: , this is a test
example: , this is a test
PREG_SET_ORDER 的例子
preg_match_all("|<[^>]+>(.*)[^>]+>|U", "a test ", $out, PREG_SET_ORDER);
print $out[0][0].", ".$out[0][1]."\n";
print $out[1][0].", ".$out[1][1]."\n"
?>
傳回值為
example: , example:
this is a test , this is a test
--------------------------------------------------------------------------------
函式:preg_replace()
--------------------------------------------------------------------------------
Perl 相容語法函式庫
preg_replace
字串比對剖析並取代。
語法: mixed preg_replace(mixed pattern, mixed replacement, mixed subject);
傳回值: 混合型態資料
函式種類: 資料處理
內容說明
本函式以 pattern 的規則來剖析比對字串 subject,欲取而代之的字串為參數 replacement。傳回值為混合型態資料,為取代的字串結果。
使用范例
下例傳回值為 $startDate = 6/19/1969
$patterns = array("/(19|20\d{2})-(\d{1,2})-(\d{1,2})/", "/^\s*{(\w+)}\s*=/");
$replace = array("\\3/\\4/\\1", "$\\1 =");
print preg_replace($patterns, $replace, "{startDate} = 1969-6-19");
?>
--------------------------------------------------------------------------------
函式:preg_split()
--------------------------------------------------------------------------------
Perl 相容語法函式庫
preg_split
將字串依指定的規則切開。
語法: array preg_split(string pattern, string subject, int [limit]);
傳回值: 陣列
函式種類: 資料處理
內容說明
本函式可將字串依指定的規則分開。切開的傳回值為陣列變數。參數 pattern 為指定的規則字串、參數 subject 則為待處理的字串、參數 limit 可省略,表示欲處理的最多合乎值。
(http://www.fanqiang.com)
進入【UNIX論壇】
|