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

PHP remove a word (not characters) from a string

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

<?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()。我该怎么做才能实现这一目标?

.

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

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