Pixel2Life Forum: easier way to filter words? - Programming and General Web Design - Pixel2Life Forum

Jump to content

  • You cannot start a new topic
  • You cannot reply to this topic

easier way to filter words?

Array

#1 User is offline   derek.sullivan 

  • Jedi In Training
  • PipPip
  • Group: Members
  • posts 343
  • Joined: 26-November 06
  • Gender:Male
  • Location:Georgia
  • Interests:preaching, programming, music, friends, outdoors, moves, books

Posted 17 May 2011 - 11:29 AM

Okay RC I need you again! I have a word filter and it works, but I had to type out each preg_replace for each word rather than having a universal preg_replace for an array of bad words. for example:

$m = "ass";
$m = preg_replace("[^ass$]", "***", $m);
echo $m; // output = ***

$b = "basset";
$b = preg_replace("[^ass$]", "***", $<img src='http://www.pixel2life.com/forums/public/style_emoticons/<#EMO_DIR#>/shades.gif' class='bbc_emoticon' alt='B)' />;
echo $b; // output = basset

this will check $m and $b for the word ass. If there is anything before, or after the word ass like asset, it will produce basset rather than ***et

So my question is, instead of having to do it like the example above, is there a way to do this in an array, check the array for the word, change the word if necessary?

Edited by derek.sullivan, 17 May 2011 - 11:30 AM.

0

#2 User is offline   rc69 

  • PHP Master PD
  • PipPipPipPip
  • Group: P2L Staff
  • posts 3,827
  • Joined: 26-September 04
  • Gender:Male
  • Location:Here
  • Interests:Web Development

Posted 17 May 2011 - 04:59 PM

If you want to replace the words you are censoring with the exact same number of '*' as there are characters, then you are pretty much stuck using an array or several calls to preg_replace().

So in short, yes, you can use an array, see: http://php.net/manua...reg-replace.php

The string or an array with strings to replace. If this parameter is a string and the pattern parameter is an array, all patterns will be replaced by that string. If both pattern and replacement parameters are arrays, each pattern will be replaced by the replacement counterpart. If there are fewer elements in the replacement array than in the pattern array, any extra patterns will be replaced by an empty string.


You can even cheat further by grouping equal length words into one element in the array. i.e.
$str_to_censor = 'One heck of a string contining all the foo and bar to censor out of foobar!';
$words = array('/\b(foo|bar)\b/' => '***', '/\b(four|five|nine)\b/' => '****');
$str = preg_replace(array_keys($words), array_values($words), $str_to_censor);
The biggest thing to note here is '\b', it stands for word boundary.
ref: http://php.net/manua...ence.escape.php

Edited by rc69, 17 May 2011 - 05:01 PM.

0

Share this topic:


  • You cannot start a new topic
  • You cannot reply to this topic

0 user(s) are reading this topic
members, guests, anonymous users