php - 使用正则表达式拆分数组

标签 php regex arrays

我想知道是否可以使用正则表达式截断数组。

特别是我有一个这样的数组:

$array = array("AaBa","AaBb","AaBc","AaCa","AaCb","AaCc","AaDa"...);

我有这个字符串:

$str = "AC";

我想要 $array 的切片,从匹配 /A.C./ 的字符串开始到最后一次出现(在示例中,索引处的“AaCc” 5):

$result = array("AaBa","AaBb","AaBc","AaCa","AaCb","AaCc");

我该怎么做?我想我可以使用 array_slice,但我不知道如何使用 RegEx。

最佳答案

这是 my bid

function split_by_contents($ary, $pattern){
  if (!is_array($ary)) return FALSE; // brief error checking

  // keep track of the last position we had a match, and the current
  // position we're searching
  $last = -1; $c = 0;

  // iterate over the array
  foreach ($ary as $k => $v){
    // check for a pattern match
    if (preg_match($pattern, $v)){
      // we found a match, record it
      $last = $c;
    }
    // increment place holder
    $c++;
  }

  // if we found a match, return up until the last match
  // if we didn't find one, return what was passed in
  return $last != -1 ? array_slice($ary, 0, $last + 1) : $ary;
}

更新

我的原始答案有一个没有用的 $limit 参数。我最初确实有一个不同的方向,我打算使用解决方案,但决定保持简单。但是,下面是 version that implements that $limit .所以……

function split_by_contents($ary, $pattern, $limit = 0){
  // really simple error checking
  if (!is_array($ary)) return FALSE;

  // track the location of the last match, the index of the
  // element we're on, and how many matches we have found
  $last = -1; $c = 0; $matches = 0;

  // iterate over all items (use foreach to keep key integrity)
  foreach ($ary as $k => $v){

    // text for a pattern match
    if (preg_match($pattern, $v)){

      // record the last position of a match
      $last = $c;

      // if there is a specified limit, capture up until
      // $limit number of matches, then exit the loop
      // and return what we have
      if ($limit > 0 && ++$matches == $limit){
        break;
      }
    }

    // increment position counter
    $c++;
  }

关于php - 使用正则表达式拆分数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8900741/

相关文章:

php - MySQL:WHERE 值大于 Min 且小于 Max

php - 我可以在所有 Controller 中使用的用户定义函数

php - 同一服务器上两个数据库之间的 MSSQL LEFT JOIN,使用 PDO 时不返回任何内容

python - 如何在 Python 中删除字符串中的任何 URL

arrays - Angular 6 : get array of objects from corresponding JSON through httpClient

php - 如何使用php将字符串转换成数组

javascript - 使用 jquery 将文本替换为变量的值

Java 正则表达式 : difference between range and union

java - 如何在 android 中按升序或降序值对 arraylist 进行排序?

python - 如何以正确的格式在文本文件中写入两个 numpy 数组?