简体   繁体   中英

Remove words from a string in PHP

I'm trying to remove some particular words from a given input string which is splitted into words. But from the splitted words array the particular words are not getting replaced.

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

Expected output:

Array ([0] => want)

I cant find out whats wrong in this. Please help me to solve this.

First of all remove spaces from the string in array $omit_words .Try this use array_diff : If you want to re-index the output you can use 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); // 

You can used array_diff and then array_values for reset array indexing.

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

You will have to remove spaces from 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 ) 

Try this

<?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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM