【发布时间】:2017-06-11 06:09:02
【问题描述】:
对于我的代码,如果以下单词是“红色”,我只想进行字符串突变。不,它背后没有逻辑,但它应该是一个简单的案例,一个困难的案例。
因此,我使用了next(),但如果最后一个词是“红色”,则它不起作用。
我的代码:
$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”所提到的,我得到“red”。我应该怎么做才能获得所需的输出?
【问题讨论】:
标签: php arrays string-matching next