首页 > 提取所有匹配的字符串,包括已经匹配的

提取所有匹配的字符串,包括已经匹配的

使用 [\w]{1,2}去匹配字符串 ABC 的时候返回的匹配结果是 ABC。 如何修改使得匹配结果变成 A, B, C, AB, BC ?


正则的匹配默认都是贪婪的,并且已经匹配过的内容不会再进行匹配的。所以你的问题无法单纯的用正则完成。但是你可以配合循环完成你的要求。做法很简单,就是每次砍掉头部一个字符,然后再用正则进行两次匹配(1次贪婪,1次非贪婪)。最后把每次的结果都合并起来并去重即可。

$re1 = '/[\w]{1,2}/'; //贪婪的
$re2 = '/[\w]{1,2}?/';  //非贪婪的
$res = []; //结果数组
$str = 'ABC';

for($i = 0; $i < strlen($str); $i++){
  $newstr = substr($str, $i);
  preg_match_all($re1, $newstr, $matches);
  if(!empty($matches)){
      $res = array_merge($res, $matches[0]);
  }
  preg_match_all($re2, $newstr, $matches);
  if(!empty($matches)){
    $res = array_merge($res, $matches[0]);
  }
}
$res = array_unique($res); //结果去重
var_dump($res); //输出结果看看

以上代码在win7 x64 sp1, php 5.4.12 cli下运行通过,结果:

array (size=5)
  0 => string 'AB' (length=2)
  1 => string 'C' (length=1)
  2 => string 'A' (length=1)
  3 => string 'B' (length=1)
  5 => string 'BC' (length=2)
【热门文章】
【热门文章】