Für meinen Code möchte ich nur eine String-Mutation haben, wenn das folgende Wort "rot" ist. Und nein, es gibt keine Logik dahinter, aber es sollte ein einfacher Fall für einen schwierigen sein. Also habe ich next()
verwendet, aber wenn das letzte Wort "rot" ist, dann funktioniert es nicht.einfache String-Mutation in PHP
Mein Code:
$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);
Wie für die letzten "rot" erwähnt, anstatt sich "ed" ich "rot". Was muss ich tun, um die gewünschte Ausgabe zu erhalten?