在特定阵列模式后插入项目

时间:2016-11-14 14:13:53

标签: php arrays key pattern-matching

我想在特定模式后插入一个项目。在我的情况下,我想在数组中每隔一秒x后插入a。在第六次a之后,我的代码无法正常运行:

$array = array("a","a","a","a","a","a","b","a","a");

$out = array();
foreach ($array as $key=>$value){
    $out[] = $value; // add current letter to new array
    if($value=='a' && $array[$key-1]=='a' && $out[$key] !='x'){ // check if current and last letter are a
        $out[] = 'x'; // if so add an x to the array
    }
}

print_r($out);

2 个答案:

答案 0 :(得分:1)

  

最后纠正答案

你在寻找什么?

<?php
$array = array("a","a","a","a","a","a","b","a","a");
foreach ($array as $key => $value){
    if ($key == 0 || $key == 1) {
        $array[$key] = $value; 
    } elseif($array[$key-1] == 'a' && $array[$key-2] == 'a' && $array[$key] == 'a') {
        $array[$key] = 'x';
    } else {
        $array[$key] = $value; 
    }
}
$count = count($array);
if ($array[$count-1] == 'a' && $array[$count-2] == 'a') {
    $array[] = 'x';
}
print_r($array);
?>

如果我理解正确,请在2 a之后将x放入新数组中。

<强>更新

请立即查看。如果最后两个元素在数组中x,则会添加一个新元素a

有例外,但仍然有效:

<?php
$array = array("a","a","a","a","a","a","b","a","a");
foreach ($array as $key => $value){
    if($array[$key-1] == 'a' && $array[$key-2] == 'a' && $array[$key] == 'a') {
        $array[$key] = 'x';
    }
}
$count = count($array);
if ($array[$count-1] == 'a' && $array[$count-2] == 'a') {
    $array[] = 'x';
}
print_r($array);
?>

更新 - 更正代码

我认为以下代码可以满足您的所有需求:

<?php
$arr = array("a","w","a","d","a","a","b","a","a", "w");
$arr_count = count($arr);   
for ($i = 0; $i < $arr_count; $i++){
    if (!empty($arr[$i+1]) && $arr[$i] == $arr[$i+1]) {
        $first_half = array_slice($arr, 0, $i+2);
        $second_half = array_slice($arr, $i+2, $arr_count);     
        if (count($second_half) > 0) {
            $arr = array_merge($first_half, ["x"], $second_half);
        }
    }
}
$count = count($arr);
if ($arr[$count-1] == 'a' && $arr[$count-2] == 'a') {
    $arr[] = 'x';
}

print_r($arr);
?>

答案 1 :(得分:0)

正如评论中提到的,你肯定可以在这种特殊情况下使用正则表达式:

$pattern = '/a{2}/';
$replacement = '$0x';

$out = str_split(preg_replace(
    $pattern,
    $replacement,
    implode('', $array)
));

基本上,我们将字符粘合在一起(使用implode)来形成字符串,然后用"aa"替换每个"aax"。之后,我们使用str_split将字符串拆分回数组。

这是demo