Skip to content

Instantly share code, notes, and snippets.

@texdc
Last active December 25, 2015 06:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save texdc/6929908 to your computer and use it in GitHub Desktop.
Save texdc/6929908 to your computer and use it in GitHub Desktop.
Filter or Sanitizer?
  • A filter removes unwanted data.
  • A sanitizer modifies data according to a standard or specification.

See FilterIterator

<?php
/**
* A filter removes unwanted data.
*/
interface FilterInterface
{
/**
* Filter the data
*
* @param mixed $data the data to filter [implied]
* @return mixed
*/
function filter();
}
<?php
/**
* Remove strings matching a regex pattern.
*/
class RegexFilter implements FilterInterface
{
/**
* @var string|array
*/
private $pattern;
/**
* @var integer
*/
private $limit;
/**
* Constructor
*
* @param string|array $pattern the regex pattern(s)
* @param integer $limit the maximum possible replacements for each pattern
*/
public function __construct($pattern, $limit = -1)
{
$this->pattern = $pattern;
$this->limit = $limit;
}
/**
* Filter a string by the pattern
*
* @param string $string the string to filter
* @return string|null
*/
public function filter($string)
{
return preg_replace($this->pattern, '', $string, $this->limit);
}
}
<?php
/**
* Replace regex matches in strings
*/
class RegexSanitizer implements SanitizerInterface
{
/**
* @var string|array
*/
private $pattern;
/**
* @var string|array
*/
private $replacement;
/**
* @var integer
*/
private $limit;
/**
* Constructor
*
* @param string|array $pattern the regex pattern(s)
* @param string|array $replacement the replacement(s)
* @param integer $limit the maximum possible replacements for each pattern
*/
public function __construct($pattern, $replacement, $limit = -1)
{
$this->pattern = $pattern;
$this->replacement = $replacement;
$this->limit = $limit;
}
/**
* Sanitize a string by the pattern
*
* @param string $string the string to sanitize
* @return string
*/
public function sanitize($string)
{
return preg_replace($this->pattern, $this->replacement, $string, $this->limit);
}
}
<?php
/**
* A sanitizer modifies data according to a standard or specification.
*/
interface SanitizerInterface
{
/**
* Sanitize the data
*
* @param mixed $data the data to sanitize [implied]
* @return mixed
*/
function sanitize();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment