【发布时间】:2016-11-14 14:13:53
【问题描述】:
我想在特定模式之后插入一个项目。在我的情况下,我想在数组中的每一秒 a 之后插入 x。在第六次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);
【问题讨论】:
-
@AniketSahrawat 正则表达式用于字符串。
-
我以为他想在每个
x之后添加a,没有看到数组。 -
@u_mulder,其实这里可以使用正则表达式。请看我的回答。
-
@sevavietl 如果 OP 向我们展示了简化的示例会怎样。如果他有对象而不是
"a"怎么办?其他数组? -
@u_mulder,对不起,我不知道我们正在阅读茶叶。但是,无论如何,我指定了在这种特殊情况下使用正则表达式。我完全同意,在更复杂的情况下,这种方法是行不通的。但是,如果任务像声明的那样简单,则无需重新发明正则表达式并处理循环。
标签: php arrays key pattern-matching