2016-12-29 76 views
0

我试图从给定的输入字符串中分离出单词中的某些特定单词。但是从分裂的单词阵列中,特定的单词不会被替换。从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) 

我无法找出什么是错在这。请帮我解决这个问题。

+0

如果您只需要更换(删除)的话,那么基于正则表达式的方法长相更轻松。基于爆炸/数组的方法只有合理,如果你真的需要这些单词作为数组,而不是字符串。 – arkascha

回答

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); // 
+0

完美...感谢哥们:) – Shihas

+0

@RazibAlMamun感谢您的评论。我已经这样做:) – Shihas

+0

好男人,一些新的程序员遵循一些时间码。 hahahaha –

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) 
?> 
+0

谢谢.. :)(Y) – Shihas

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); 
+0

预期的结果应该是数组不是字符串 –

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) 
+0

没有兄弟..如果我使用此代码,那么单词**“wish”**也将被拒绝,因为它包含**“is”* * – Shihas

+0

现在完美。 – Shihas

相关问题