【问题标题】:PHP remove a word (not characters) from a stringPHP从字符串中删除一个单词(不是字符)
【发布时间】:2018-03-16 18:53:01
【问题描述】:

以下代码的问题在于,它从字符串中删除了字符,而不是单词

<?php
    $str = "In a minute, remove all of the corks from these bottles in the cellar";

    $useless_words = array("the", "of", "or", "in", "a");

    $newstr = str_replace($useless_words, "", $str);

   //OUTPUT OF ABOVE:  "In mute, remove ll   cks from se bottles   cellr"
?>

我需要输出:分钟,从这些酒瓶地窖中取出所有软木塞

我假设我不能使用str_replace()。我该怎么做才能做到这一点?

.

【问题讨论】:

    标签: string replace str-replace words


    【解决方案1】:

    preg_replace 将完成这项工作:

    $str = "The game start in a minute, remove all of the corks from these bottles in the cellar";
    $useless_words = array("the", "of", "or", "in", "a");
    $pattern = '/\h+(?:' . implode($useless_words, '|') . ')\b/i';
    $newstr = preg_replace($pattern, "", $str);
    echo $newstr,"\n";
    

    输出:

    The game start minute, remove all corks from these bottles cellar
    

    说明:

    模式看起来像:/\h+(?:the|of|or|in|a)\b/i

    /                   : regex delimiter
      \h+               : 1 or more horizontal spaces
      (?:               : start non capture group
        the|of|or|in|a  : alternatives for all the useless words
      )                 : end group
      \b                : word boundary, make sure we don't have a word character before
    /i                  : regex delimiter, case insensitive
    

    【讨论】:

      【解决方案2】:
      $useless_words = array(" the ", " of ", " or ", " in ", " a ");
      $str = "In a minute, remove all of the corks from these bottles in the 
      cellar";
      
      $newstr = str_replace($useless_words, " ", $str);
      
      $trimmed_useless_words = array_map('trim',$useless_words);
      $newstr2 = '';
      foreach ($trimmed_useless_words as &$value) {
         if (strcmp($value, substr($newstr,0,strlen($value)))){
             $newstr2 = substr($newstr, strlen($value) );
             break;
         }
      }
      if ($newstr2 == ''){
          $newstr2 = $newstr; 
      }
      echo $newstr2;
      

      【讨论】:

      • 这适用于这个特定的字符串,但如果需要评估一个新字符串并且该字符串以“the”开头,则不会删除该单词。但这很有帮助。
      • 更新答案以覆盖字符串中的第一个单词
      猜你喜欢
      • 2017-07-17
      • 2011-10-12
      • 1970-01-01
      • 2015-06-08
      • 1970-01-01
      • 2014-11-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多