2017-01-25 3 views
1

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?

Répondre

0

Vous pouvez sélectionner la touche suivante "manuellement":

$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); 
tableau

(5) {[0] => string (3) "l'homme" [1] => string (2) " ed "[2] => chaîne (5)" apple "[3] => chaîne (3)" ham "[4] => chaîne (2)" ed "}

1

La raison pour laquelle Le fonctionnement dépend de la prochaine itération de la boucle pour faire ce dont vous avez besoin en fonction de votre évaluation dans l'itération actuelle. Si l'élément que vous voulez modifier est le dernier élément du tableau, il n'y aura pas d'itération suivante avec laquelle le modifier.

Au lieu de vérifier le mot suivant, vous pouvez suivre le mot précédent et l'utiliser.

$previous = ''; 
foreach ($input as $key => $word) { 
    if ($word == 'red' && in_array(substr($previous, -1), $endings)) { 
     $input[$key] = substr($word, 1); 
    } 
    $previous = $word; 
}