- A filter removes unwanted data.
- A sanitizer modifies data according to a standard or specification.
See FilterIterator
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(); | |
} |