[英]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
的字符串中刪除空格。 $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)
?>
您將必須從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 )
嘗試這個
<?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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.