【问题标题】:simple string mutation in phpphp中的简单字符串突变
【发布时间】:2017-06-11 06:09:02
【问题描述】:

对于我的代码,如果以下单词是“红色”,我只想进行字符串突变。不,它背后没有逻辑,但它应该是一个简单的案例,一个困难的案例。 因此,我使用了next(),但如果最后一个词是“红色”,则它不起作用。

我的代码:

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

正如最后一个“red”而不是“ed”所提到的,我得到“red”。我应该怎么做才能获得所需的输出?

【问题讨论】:

    标签: php arrays string-matching next


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

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

      $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) "火腿" [4]=> 字符串(2) "ed" }

      【讨论】:

        猜你喜欢
        • 2017-05-12
        • 2011-02-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-12
        • 2011-08-04
        • 1970-01-01
        相关资源
        最近更新 更多