对于我的代码,如果下面的单词是" red",我只想要一个字符串变异。并且没有任何逻辑背后,但它应该是一个困难的简单案例。
所以我使用next()
,但如果最后一个单词是" red"然后它不起作用。
我的代码:
$input = ['man', 'red', 'apple', 'ham', 'red'];
$endings = ['m', 'n'];
$shouldRemove = false;
foreach ($input as $key => $word) {
// if this variable is true, it will remove the first character of the current word.
if ($shouldRemove === true) {
$input[$key] = substr($word, 1);
}
// we reset the flag
$shouldRemove = false;
// getting the last character from current word
$lastCharacterForCurrentWord = $word[strlen($word) - 1];
if (in_array($lastCharacterForCurrentWord, $endings) && next($input) == "red") {
// if the last character of the word is one of the flagged characters,
// we set the flag to true, so that in the next word, we will remove
// the first character.
$shouldRemove = true;
}
}
var_dump($input);
如前所述" red"而不是得到" ed"我得到红色"。我该怎么做才能获得所需的输出?
答案 0 :(得分:1)
它不起作用的原因是它依赖于循环的下一次迭代来根据您在当前迭代中的评估来执行您需要的操作。如果要更改的项是数组中的最后一项,则不会有下一次迭代来更改它。
您可以跟踪前一个单词并使用该单词,而不是检查以下单词。
$previous = '';
foreach ($input as $key => $word) {
if ($word == 'red' && in_array(substr($previous, -1), $endings)) {
$input[$key] = substr($word, 1);
}
$previous = $word;
}
答案 1 :(得分:0)
您可以选择下一个键"手动":
$input = ['man', 'red', 'apple', 'ham', 'red'];
$endings = ['m', 'n'];
$shouldRemove = false;
foreach ($input as $key => $word) {
// if this variable is true, it will remove the first character of the current word.
if ($shouldRemove === true) {
$input[$key] = substr($word, 1);
}
// we reset the flag
$shouldRemove = false;
// getting the last character from current word
$lastCharacterForCurrentWord = $word[strlen($word) - 1];
if (in_array($lastCharacterForCurrentWord, $endings) && $input[$key+1] == "red") {
// if the last character of the word is one of the flagged characters,
// we set the flag to true, so that in the next word, we will remove
// the first character.
$shouldRemove = true;
}
}
var_dump($input);
array(5){[0] => string(3)" man" [1] =>字符串(2)" ed" [2] => string(5)" apple" [3] => string(3)" ham" [4] =>字符串(2)" ed" }