2017-01-25 1 views
1

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?

Antwort

0

Sie können die nächste Taste wählen "manuell":

$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] => string (2) " ed "[2] => string (5)" apple "[3] => string (3)" ham "[4] => string (2)" ed "}

1

Der Grund dafür ist nicht ' Es funktioniert so, dass es auf der nächsten Iteration der Schleife beruht, um basierend auf Ihrer Bewertung in der aktuellen Iteration das zu tun, was Sie benötigen. Wenn das Element, das Sie ändern möchten, das letzte Element im Array ist, wird es keine nächste Iteration geben, mit der es geändert werden kann.

Anstatt das folgende Wort zu überprüfen, können Sie das vorherige Wort verfolgen und dieses verwenden.

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