Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

checking for certian words but allowing others?

Status
Not open for further replies.

cleansedbb

Technical User
Feb 11, 2002
95
US
I'm working on a word filter for my site but I want to
delete bad words such as a$$ but I want to allow the word
assistant but so far with preg_replace i'm getting

istant as it's removing the other

anyone have any suggestions??

Thank You!
 
I am not a solid php expert, but the first thing i think of in your case is creating an array of unwanted bad words; then would loop through the array to find and replace bad words. You can also have 2 dimensional array of bad words to replace bad word with a specific one
example:
$badWords = array (
array("badword1","word 1 to replace"),
array("badword2","word 2 to replace"),
array("badword3","word 3 to replace "),
);
then while looping use eregi_replace($badWords[$i][0],$bads[$i][1],$wordToMatch)
this way is you have assistant then it won't be replaced, but if you have a$$ then it would.
 
Warning
This post contains profanities for illustration only.

The only adjustment that you have to make is to embed the offending words in \b (word boundary).
Code:
$str = 'I am an assistant and I am an ass and an asshole.';
$badPattern[] = '/\bass\b/i';
$badPattern[] = '/\basshole\b/i';
$str = preg_replace($badPattern,'***',$str);
echo $str;

The \b will only match for 'whole' words, i.e. with word boundaries such as white space, punctuation. More about word boundaries from the PHP manual:
PHP manual said:
A word boundary is a position in the subject string where the current character and the previous character do not both match \w or \W (i.e. one matches \w and the other matches \W), or the start or end of the string if the first or last character matches \w, respectively.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top