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

时间:2016-12-29 08:40:11

标签: php arrays codeigniter str-replace

我试图从给定的输入字符串中删除一些特定的单词,这些单词被分成单词。但是从分裂的单词数组中,特定单词不会被替换。

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

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

4 个答案:

答案 0 :(得分:3)

首先从数组$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); // 

答案 1 :(得分:1)

您可以使用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)
?>

答案 2 :(得分:1)

您必须从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 ) 

答案 3 :(得分:0)

试试这个

<?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);
相关问题