PHP4手册:函数库及函数(三十九) Perl 相容语法函式库


--------------------------------------------------------------------------------
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 可省略,表示欲处理的最多合乎值。