Page 1 of 1

remove some words from string

Posted: Fri Dec 17, 2010 7:32 am
by Rahul Dev
hi folks, i have a variable in which some common words are stored and another variable in which a sentence is stored. I want to remove the common words from the sentence> Is there any way of doing this in PHP?

Code: Select all

<?php
$common_words = "to, this, all, the, from";
$sentence = "I want to remove all the common words from this sentence";
?>
the final output should be:
"I remove common words sentence."

Re: remove some words from string

Posted: Fri Dec 17, 2010 7:39 am
by Apollo
Regular expressions are your friend!

Code: Select all

$sentence = preg_replace('/\s*('.preg_replace(array('/,/','/\s+/'),array('|',''),$common_words).')\s*/i',' ',$sentence);

Re: remove some words from string

Posted: Fri Dec 17, 2010 8:14 am
by VladSun

Code: Select all

echo str_replace(explode(",", $common_words), '', $sentence);