Shihas
Shihas

Reputation: 814

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.

Upvotes: 1

Views: 8974

Answers (4)

d.coder
d.coder

Reputation: 2038

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 ) 

Upvotes: 1

Suchit kumar
Suchit kumar

Reputation: 11859

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

Upvotes: 3

muttalebm
muttalebm

Reputation: 552

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

Upvotes: 1

Razib Al Mamun
Razib Al Mamun

Reputation: 2713

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

Upvotes: 1

Related Questions