PHP从字符串中删除一个单词(不是字符)

时间:2018-03-16 18:53:01

标签: string replace str-replace words

下面代码的问题在于它从字符串中删除字符而不是

<?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()。我能做些什么来实现这个目标?

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分: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