现在的位置: 首页php-基础语法>正文
PHP中全局正则表达式如何匹配  
发表于764 天前 php-基础语法 评论关闭

PHP中进行匹配全局正则表达式的函数为preg_match_all,语法为:

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

Pattern是用来匹配的正则表达式,input是用来匹配的字符串,matches是匹配结果的存储数组。

Flag为三个标记:

  • PHP的PREG_PATTERN_ORDER标记

例如:

  1. <?php
  2. $str = “Please call me at 507-4235 or 716-6577″;
  3. preg_match_all(“/\d{3}(\-\d{4})/”,$str,$phones,PREG_PATTERN_ORDER);
  4. print_r($phones);
  5. echo “\n”;
  6. ?>

结果如下:

Array ( [0] => Array ( [0] => 507-4235 [1] => 716-6577 ) [1] => Array ( [0] => -4235 [1] => -6577 ) )

可以看到这个数组是个二维数组。PREG_PATTERN_ORDER标记:使其结果$matches[0]存储全部模式匹配的数组,$matches[1]存储第一个子模式匹配的字符串组成的数组,$matches{2}以此类推。

  • PHP的PREG_SET_ORDER标记

例如:

  1. <?php
  2. $str = “Please call me at 507-4235 or 716-6577″;
  3. preg_match_all(“/\d{3}(\-\d{4})/”,$str,$phones,PREG_SET_ORDER”);
  4. print_r($phones);
  5. ?>

结果:

Array ( [0] => Array ( [0] => 507-4235 [1] => -4235 ) [1] => Array ( [0] => 716-6577 [1] => -6577 ) )

这个标记和第一个有什么区别呢?

是,PREG_SET_ORDER标记:使其结果$matches[0]存储第一组匹配的数组,$matches[1]存储第二组匹配的数组,$matches{2}以此类推。

  • PHP的PREG_OFFSET_CAPTURE标记

例如:

  1. <?php
  2. $str = “Please call me at 507-4235 or 716-6177″;
  3. preg_match_all(“/\d{3}(\-\d{4})/”,$str,$phones,PREG_OFFSET_CAPTURE); //偏移量为字符串的开始。
  4. print_r($phones);
  5. ?>

结果:

Array ( [0] => Array ( [0] => Array ( [0] => 507-4235 [1] => 18 ) [1] => Array ( [0] => 716-6177 [1] => 30 ) ) [1] => Array ( [0] => Array ( [0] => -4235 [1] => 21 ) [1] => Array ( [0] => -6177 [1] => 33 ) ) )

这个标记又有什么不同呢?

PREG_OFFSET_CAPTURE标记:使其结果$matches[0]存储全部模式匹配的数组和偏移量,$matches[1]存储第一个子模式匹配的字符串组成的数组和偏移量。

注意:红色的是偏移量,意思为数组从哪里开始。

报歉!评论已关闭.

不想听你唠叨×