2016-12-29 105 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

相關問題