Reputation: 2700
How to filter phrase
use php? Can anyone give me a function call?
for example, If I want filter the phrase 'no' 'this' from a sentence There are no user contributed notes for this page.
So that the sentence return like There are user contributed notes for page.
Thanks.
<?php
function filterBadWords($str)
{
$badwords = array('no','this');
$replacements = " ";
foreach ($badwords AS $badword)
{
$str = eregi_replace($badword, str_repeat(' ', strlen($badword)), $str);
}
return $str;
}
$string = "There are user contributed notes for page.";
print filterBadWords($string); // this will filter `no` from `notes`
?>
Upvotes: 1
Views: 304
Reputation: 141827
$text = preg_replace('/\b(?:no|this)\b ?/i', '', $text);
Edit:
Now it removes a space if it finds one after the word, so that you don't end up with two spaces in a row.
$text = 'There are no user contributed notes for this page.';
$text = preg_replace('/\b(?:no|this)\b ?/i', '', $text);
echo $text;
Outputs: There are user contributed notes for page.
Update
If you want to use an array to make it easier to manage filtered words you could do this:
function filterWords($string){
$bad_words = array('no', 'this');
return preg_replace('/\b(?:'.implode('|', $bad_words).')\b ?/i', '', $string);
}
echo filterWords('There are no user contributed notes for this page.');
Upvotes: 2