Pour mon code, je veux seulement avoir une mutation de chaîne si le mot suivant est "rouge". Et non, il n'y a pas de logique derrière cela mais cela devrait être un cas simple pour un cas difficile. Donc donc j'ai utilisé next()
mais si le dernier mot est "rouge" alors ça ne marche pas.mutation de chaîne simple en php
Mon 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);
Comme mentionné pour la dernière "rouge" au lieu d'obtenir "ed" je reçois "rouge". Que dois-je faire pour obtenir la sortie désirée?