Skip to content

Instantly share code, notes, and snippets.

@joshuaadickerson
Created March 13, 2016 18:32
Show Gist options
  • Save joshuaadickerson/cf75b362d26cabbd7945 to your computer and use it in GitHub Desktop.
Save joshuaadickerson/cf75b362d26cabbd7945 to your computer and use it in GitHub Desktop.
Elkarte Censor as a class
<?php
/**
* $censor = new Censor($modSettings['censor_vulgar'], $modSettings['censor_proper'], $modSettings);
* $censor->censor($message['body']);
*/
class Censor
{
const WHOLE_WORD = 'censorWholeWord';
const IGNORE_CASE = 'censorIgnoreCase';
const SHOW_NO_CENSORED = 'show_no_censored';
const ALLOW_NO_CENSORED = 'allow_no_censored';
protected $vulgar = array();
protected $proper = array();
protected $options = array(
self::WHOLE_WORD => false,
self::IGNORE_CASE => false,
self::SHOW_NO_CENSORED => false,
self::ALLOW_NO_CENSORED => false,
);
public funciton __construct(array $vulgar, array $proper, array $options = array())
{
if (count($vulgar) !== count($proper))
{
throw new \InvalidArgumentException('Censored vulgar and proper arrays must be equal sizes');
}
$this->setOptions($options);
$this->setVulgarProper($vulgar, $proper);
}
protected function setOptions(array $options)
{
$this->options = array_merge($this->options, $options);
}
protected function setVulgarProper(array $vulgar, array $proper)
{
// Quote them for use in regular expressions.
if ($this->options[self::WHOLE_WORD])
{
for ($i = 0, $n = count($vulgar); $i < $n; $i++)
{
$vulgar[$i] = str_replace(array('\\\\\\*', '\\*', '&', '\''), array('[*]', '[^\s]*?', '&amp;', '&#039;'), preg_quote($vulgar[$i], '/'));
$vulgar[$i] = '/(?<=^|\W)' . $vulgar[$i] . '(?=$|\W)/u' . (!$this->options[self::IGNORE_CASE] ? '' : 'i');
// @todo I'm thinking the old way is some kind of bug and this is actually fixing it.
//if (strpos($vulgar[$i], '\'') !== false)
//$vulgar[$i] = str_replace('\'', '&#039;', $vulgar[$i]);
}
}
$this->vulgar = $vulgar;
$this->proper = $proper;
}
public function censor(&$text, $force = false)
{
if (!$this->options[self::WHOLE_WORD])
{
$text = !$this->options[self::IGNORE_CASE]] ? str_replace($this->vulgar, $this->proper, $text) : str_ireplace($this->vulgar, $this->proper, $text);
}
else
{
$text = preg_replace($this->vulgar, $this->proper, $text);
}
return $text;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment