note 45213 added to function.preg-replace
| From: | lgomezedgeracingcom at osu1 dot php dot net | Date: | Mon, 30 Aug 2004 07:31:21 +0000 |
| Subject: | note 45213 added to function.preg-replace | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-75652@lists.php.net to get a copy of this message | ||
Here's a way of replacing any collection of words from a string. Good for filtering bad words.
I don't know if it can be compacted even more.
<?php
function filter($str,$words,$replacement='*'){
foreach($words as $word){
$str=preg_replace("/\\b$word\\b/i",'
'.str_repeat($replacement,strlen($word)).' ',$str);
}
return $str;
}
$bad_words=array('butt','poop','crap');
$text='One thing to take note bhjbdscrapmkjv of is that if you use poop as paint, you may not
get the crap
you expect butt.';
echo filter($text,$bad_words);
?>
----
Manual Page -- http://www.php.net/manual/en/function.preg-replace.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+45213
Delete -- http://master.php.net/manage/user-notes.php?action=delete+45213&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+45213&report=yes
Search -- http://master.php.net/manage/user-notes.php