阵列元素中的字符串突变



我想操纵数组元素。因此,如果某个数组元素以字母 nm结尾,并且以下元素为例如 apple,那么我想删除" 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);
                    }
        }   

}  

我必须如何更改代码以使我获得所需的输出?

听起来像是一项很酷的运动任务。

阅读起始评论后,我对此的方法就是这样:

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

此脚本的输出将为

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

我希望评论的解释就足够了。

最新更新