2016-12-04 2 views
1

配列要素を操作したいと思います。だから、特定の配列要素が文字nまたはmで終わると次の要素は、例えば、appleのためであるならば、私は出力として得られるように、「りんご」の「A」を削除する:Array ([0] => man [1] => pple)配列要素の文字列の変異

マイコード:

$input = array("man","apple"); 

$ending = array("m","n"); 

$example = array("apple","orange"); 


for($i=0;$i<count($input);$i++) 
{ 
    $second = isset($input[$i+1])?$input[$i+1][0]:null; 


    $third = substr($input[$i],-2); 




     if(isset($third) && isset($second)){ 
        if ( in_array($third,$ending) && in_array($second,$example)){ 
        $input[$i+1] = substr($input[$i+1],0,-2); 
        } 

     } 



} 

希望の出力を得るためにコードを変更する必要がありますか?

+0

配列が次のようなものなら、出力はどうなるでしょう: 'array(" man "、" ham "、" apple ");'、 'array(" man "、" am "、" pple ");'? –

+0

@RajdeepPaulいいえ、それは出力 –

+0

と同じになるでしょうこれの背後にある論理は何ですか? 'man'は' n'で終わり、 'ham'の開始文字hは削除されます。同様に、今では、「am」は文字「m」で終わっているので、「apple」の文字「a」は削除され、「pple」として残されます。質問の論理を明確にしてください。 –

答えて

1

涼しい運動のような音。開始コメントを読んだ後にこれに私のアプローチは、このようなものになるだろう

:このスクリプトの出力は

array(5) { [0]=> string(3) "man" [1]=> string(6) "amster" [2]=> string(5) "apple" [3]=> string(3) "ham" [4]=> string(2) "ed" }

だろう

$input = ['man', 'hamster', '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)) { 
     // 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); 
die(); 

私はコメントと説明があると思います十分な。

+0

単語が特定の文字で終わっていない場合、次の最初の文字は削除されません。次の単語が 'apple'または' orange'の場合のみ。 –

関連する問題