php preg_match_all() 用法

来源:互联网 发布:tc编程案例 编辑:程序博客网 时间:2024/05/21 18:31

preg_match_all() 函数用于进行正则表达式全局匹配,成功返回整个模式匹配的次数(可能为零),如果出错返回 FALSE 。

int preg_match_all( string pattern, string subject, array matches [, int flags ] )

pattern正则表达式subject需要匹配检索的对象matches存储匹配结果的数组flags

可选,指定匹配结果放入 matches 中的顺序,可供选择的标记有:

  1. PREG_PATTERN_ORDER:默认,对结果排序使 $matches[0] 为全部模式匹配的数组,$matches[1] 为第一个括号中的子模式所匹配的字符串组成的数组,以此类推
  2. PREG_SET_ORDER:对结果排序使 $matches[0] 为第一组匹配项的数组,$matches[1] 为第二组匹配项的数组,以此类推
  3. PREG_OFFSET_CAPTURE:如果设定本标记,对每个出现的匹配结果也同时返回其附属的字符串偏移量


$str = '2015-9-15 XXXXXXXX,2015-9-15 XXXXXXXX,2015-9-15 XXXXXXXX,2015-9-15 XXXXXXXX,';preg_match_all('/\d{4}-\d+\-\d+(.*?),/is', $str, $matched);echo "<pre>";print_r($matched);echo "</pre>";exit;

参数为 默认 
$matched =   
Array(    [0] => Array        (            [0] => 2015-9-15 XXXXXXXX,            [1] => 2015-9-15 XXXXXXXX,            [2] => 2015-9-15 XXXXXXXX,            [3] => 2015-9-15 XXXXXXXX,        )    [1] => Array        (            [0] =>  XXXXXXXX            [1] =>  XXXXXXXX            [2] =>  XXXXXXXX            [3] =>  XXXXXXXX        ))
数组$matched[0] 表示 全匹配的数组。表示:     \d{4}-\d+\-\d+(.*?),   所匹配的信息,包括 非括号中的信息
$matched[1]  表示第一个括号中的数组信息。如果有第二个括号,会有$matched[2] 匹配括号2中的信息

$str = '2015-9-15 XXXXXXXX,2015-9-15 XXXXXXXX,2015-9-15 XXXXXXXX,2015-9-15 XXXXXXXX,';preg_match_all('/\d{4}-\d+\-\d+(.*?),/is', $str, $matched,PREG_SET_ORDER);echo "<pre>";print_r($matched);//print_r($matched[1]);echo "</pre>";exit;

$matched =   
Array(    [0] => Array        (            [0] => 2015-9-15 XXXXXXXX,            [1] =>  XXXXXXXX        )    [1] => Array        (            [0] => 2015-9-15 XXXXXXXX,            [1] =>  XXXXXXXX        )    [2] => Array        (            [0] => 2015-9-15 XXXXXXXX,            [1] =>  XXXXXXXX        )    [3] => Array        (            [0] => 2015-9-15 XXXXXXXX,            [1] =>  XXXXXXXX        ))
 


0 0
原创粉丝点击