Skip to content

Commit

Permalink
Merge pull request #18 from TheInfernoX/patch-1
Browse files Browse the repository at this point in the history
Added "matched" feature, simplified randCensor
  • Loading branch information
snipe committed Jun 12, 2015
2 parents 5c32b8b + 5559522 commit f56bc5c
Showing 1 changed file with 16 additions and 24 deletions.
40 changes: 16 additions & 24 deletions src/CensorWords.php
Original file line number Diff line number Diff line change
Expand Up @@ -68,20 +68,8 @@ public function setReplaceChar($replacer) {
*/
public function randCensor($chars, $len) {

mt_srand(); // useful for < PHP4.2
$lastChar = strlen($chars) - 1;
$randOld = -1;
$out = '';

// create $len chars
for ($i = $len; $i > 0; $i--) {
// generate random char - it must be different from previously generated
while (($randNew = mt_rand(0, $lastChar)) === $randOld) { }
$randOld = $randNew;
$out .= $chars[$randNew];
}

return $out;
return str_shuffle(str_repeat($chars, intval($len/strlen($chars))).
substr($chars, 0, ($len%strlen($chars))));

}

Expand All @@ -93,6 +81,7 @@ public function randCensor($chars, $len) {
*/
public function censorString($string) {
$badwords = $this->badwords;
$anThis = &$this;

$leet_replace = array();
$leet_replace['a']= '(a|a\.|a\-|4|@|Á|á|À|Â|à|Â|â|Ä|ä|Ã|ã|Å|å|α|Δ|Λ|λ)';
Expand Down Expand Up @@ -124,23 +113,26 @@ public function censorString($string) {

$words = explode(" ", $string);

// is $censorChar a single char?
$isOneChar = (strlen($this->replacer) === 1);

for ($x=0; $x<count($badwords); $x++) {

$replacement[$x] = $isOneChar
? str_repeat($this->replacer,strlen($badwords[$x]))
: $this->randCensor($this->replacer,strlen($badwords[$x]));

$badwords[$x] = '/'.str_ireplace(array_keys($leet_replace),array_values($leet_replace), $badwords[$x]).'/i';
}

$counter=0;
$match = array();
$newstring = array();
$newstring['orig'] = html_entity_decode($string);
$newstring['clean'] = preg_replace($badwords, $replacement, $newstring['orig']);
// $anThis for <= PHP5.3
$newstring['clean'] = preg_replace_callback($badwords, function($matches) use (&$anThis,&$counter,&$match) {
$match[$counter++] = $matches[0];

// is $anThis->replacer a single char?
return (strlen($anThis->replacer) === 1)
? str_repeat($anThis->replacer, strlen($matches[0]))
: $anThis->randCensor($anThis->replacer, strlen($matches[0]));
}, $newstring['orig']);
$newstring['matched'] = $match;

return $newstring;

}
}
}

0 comments on commit f56bc5c

Please sign in to comment.