remove some words from string

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Rahul Dev
Forum Newbie
Posts: 18
Joined: Thu Dec 09, 2010 4:54 am

remove some words from string

Post 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."
User avatar
Apollo
Forum Regular
Posts: 794
Joined: Wed Apr 30, 2008 2:34 am

Re: remove some words from string

Post by Apollo »

Regular expressions are your friend!

Code: Select all

$sentence = preg_replace('/\s*('.preg_replace(array('/,/','/\s+/'),array('|',''),$common_words).')\s*/i',' ',$sentence);
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Re: remove some words from string

Post by VladSun »

Code: Select all

echo str_replace(explode(",", $common_words), '', $sentence);
There are 10 types of people in this world, those who understand binary and those who don't
Post Reply