从 PHP 中的字符串中删除单词

Remove words from a string in PHP

我正在尝试从给定的输入字符串中删除一些特定的单词,这些字符串被拆分成单词。但是从拆分的单词数组中,特定的单词没有被替换。

$string = $this->input->post('keyword');  
echo $string; //what i want is you

$string = explode(" ", $string);  

$string = array_values(array_filter(preg_replace('/[^A-Za-z0-9\']/','', $string)));  

$omit_words = array(' the ',' i ',' we ',' you ',' what ',' is ');  

$keyword = array_values(array_filter(str_ireplace($omit_words,'',$string)));  
print_r($keyword); // Array ([0] => what [1] => i [2] => want [3] => is [4] => you)  

预期输出:

Array ([0] => want)

我不知道这有什么问题。请帮我解决这个问题。

首先从数组 $omit_words 中的字符串中删除空格。尝试使用 array_diff:如果要重新索引输出,可以使用 array_values

$string='what i want is you'; //what i want is you

$string = explode(" ", $string);  

$omit_words = array('the','i','we','you','what','is');  
$result=array_diff($string,$omit_words);

print_r($result); // 

您可以使用 array_diff 然后 array_values 来重置数组索引。

<?php
$string = $this->input->post('keyword');
$string = explode(" ", $string);  

$omit_words = array('the','i','we','you','what','is');  
$result = array_values(array_diff($string,$omit_words));

print_r($result);  //Array ([0] => want)
?>

试试这个

<?php
$string="what i want is you";
$omit_words = array('the','we','you','what','is','i');   // remove the spaces
rsort($omit_words); // need to sort so that correct words are replaced 
$new_string=str_replace($omit_words,'',$string);

print_r($new_string);

您必须从 omit_words:

中删除空格
$string = "what i want is you";

$string = explode(" ", $string);  

$string = array_values(array_filter(preg_replace('/[^A-Za-z0-9\']/','', $string)));

$omit_words = array('the','is','we','you','what','i');  

$keyword = array_values(array_filter(str_ireplace($omit_words, '', $string)));
print_r($keyword); // Array ( [0] => want )