Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/261.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/57.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
php中的简单字符串变异_Php_Arrays_String Matching_Next - Fatal编程技术网

php中的简单字符串变异

php中的简单字符串变异,php,arrays,string-matching,next,Php,Arrays,String Matching,Next,对于我的代码,如果下面的单词是“red”,我只希望有一个字符串变异。不,这背后没有逻辑,但这应该是一个简单的案例,一个困难的案例。 因此,我使用了next(),但是如果最后一个单词是“red”,那么它就不起作用了 我的代码: $input = ['man', 'red', 'apple', 'ham', 'red']; $endings = ['m', 'n']; $shouldRemove = false; foreach ($input as $key => $word) {

对于我的代码,如果下面的单词是“red”,我只希望有一个字符串变异。不,这背后没有逻辑,但这应该是一个简单的案例,一个困难的案例。 因此,我使用了
next()
,但是如果最后一个单词是“red”,那么它就不起作用了

我的代码:

$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”,我得到的是“红色”。我应该怎么做才能获得所需的输出?

您可以“手动”选择下一个键:

数组(5){[0]=>string(3)“man”[1]=>string(2)“ed”[2]=>string(5)“apple”[3]=>string(3)“ham”[4]=>string(2)“ed”}


它不起作用的原因是,它依赖于循环的下一次迭代,根据当前迭代中的评估来完成您需要它做的事情。如果要更改的项是数组中的最后一项,则不会有下一次迭代来更改它

您可以跟踪上一个单词并使用它,而不是检查下面的单词

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