2017-01-25 10 views
1

내 코드의 경우 다음 단어가 "빨간색"인 경우에만 문자열 변이를 원합니다. 그리고 아무 논리도 그것 뒤에 없다. 그러나 어려운 하나를위한 간단한 경우이어야한다. 그러므로 나는 next()을 사용했으나 마지막 단어가 "red"이면 작동하지 않습니다.PHP에서 간단한 문자열 변이

내 코드 :

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

대신 "ED"를 얻는 마지막 "빨간색"에 대해 언급 한 바와 같이 나는 "빨간색"얻는다. 원하는 출력을 얻으려면 어떻게해야합니까?

답변

0

당신은 "수동"다음 키를 선택할 수

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

어레이 (5) {[0] => 문자열 (3) "사람"[1] => 캐릭터 (2) " (3) "ham"[4] => 문자열 (2) "ed"}

1

그 이유는 무엇입니까? 루프의 다음 반복에 의존하여 현재 반복에서 평가를 기반으로 필요한 것을 수행합니다. 변경하려는 항목이 배열의 마지막 항목 인 경우 다음 반복을 변경할 항목이 없습니다.

다음 단어를 확인하는 대신 이전 단어를 추적하여 사용할 수 있습니다.

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