找到数组php中的第一个和最后一个匹配序列

时间:2017-03-13 13:06:27

标签: php arrays string sorting

我有一个数组来查找字母序列,然后获取最后和第一个组合。我正在尝试这样的事情。

$aarr = ['x','y','z','t','m','n','x','y','z'];
$str = implode('',$aarr);
$all_subset = powerSet($aarr);
foreach ($all_subset as $set) {
    $sre_temp = implode('', $set);
    $tru =  hasOrderedCharactersForward($sre_temp);
    if($tru){
     echo $sre_temp.'<br>';
    }
}

function powerSet($array) {
    // add the empty set
    $results = array(array());

    foreach ($array as $element) {
        foreach ($results as $combination) {
            $results[] = array_merge(array($element), $combination);
        }
    }

    return $results;
}
function hasOrderedCharactersForward($str, $i = 2) {
      $alpha = 'abcdefghijklmnopqrstuvwxyz';
      $len = strlen($str);

      for($j=0; $j <= $len - $i; $j++){
          if(strrpos($alpha, substr($str, $j, $i)) !== false){
              return true;
          }
      }

      return false;
}

我认为powerSet()不像我想的那样工作。即使它应该将'xyz'显示为组合但不是;

1 个答案:

答案 0 :(得分:1)

如果符合您的需要,请查看此内容并使用它。

$aarr = ['x','y','z','t','m','n','x','y','z'];
$subsets = [];
$i=0;
#here we merge all chars to sub-sequence 
foreach($aarr as $k=>$v){
    $subsets[$i][]=$v;
    if(isset($aarr[$k+1]) && ord($v)+1!==ord($aarr[$k+1])){
        $i++;
    }
}
$subsets = array_map(function($a){ return implode('',$a);},$subsets);
print_r($subsets);

结果:

  

数组([0] =&gt; xyz [1] =&gt; t [2] =&gt; mn [3] =&gt; xyz)

获取第一个和最后一个值:

#get first
$first=null;
$i=0;
do{
    if(strlen($subsets[$i])>1){#find sequence
        $first = $subsets[$i];
    }
    $i++;
}while(!$first && isset($subsets[$i]));
#get last
$last=null;
$i=count($subsets)-1;
do{
    if(strlen($subsets[$i])>1){#find sequence
        $last = $subsets[$i];
    }
    $i--;
}while(!$last && isset($subsets[$i]));
print "$first, $last";

结果:

  

xyz,xyz