Zend_Filter dashes and underscore
Sometimes I need to filter alnum values together with dashes ( – ) and underscores ( _ ).
The following class (similar to Alnum.php from ZF) will allow to have these characters in the Zend Filder.
<?php
/**
* Allows the fitler of alnum, dashes and underscores + whitespaces
*/
require_once ‘Zend/Filter/Interface.php’;
require_once ‘Zend/Locale.php’;
class My_Filter_AlnumD implements Zend_Filter_Interface
{
/**
* Whether to allow white space characters; off by default
*
* @var boolean
*/
public $allowWhiteSpace;/**
* Is PCRE is compiled with UTF-8 and Unicode support
*
* @var mixed
**/
protected static $_unicodeEnabled;/**
* Locale in browser.
*
* @var Zend_Locale object
*/
protected $_locale;/**
* The Alphabet means english alphabet.
*
* @var boolean
*/
protected static $_meansEnglishAlphabet;public function __construct($allowWhiteSpace = false)
{
$this->allowWhiteSpace = (boolean) $allowWhiteSpace;
if (null === self::$_unicodeEnabled) {
self::$_unicodeEnabled = (@preg_match(‘/\pL/u’, ‘a’)) ? true : false;
}if (null === self::$_meansEnglishAlphabet) {
$this->_locale = new Zend_Locale(‘auto’);
self::$_meansEnglishAlphabet = in_array($this->_locale->getLanguage(),
array(‘ja’, ‘ko’, ‘zh’)
);
}}
public function filter($value)
{
$whiteSpace = $this->allowWhiteSpace ? ‘\s’ : ”;
if (!self::$_unicodeEnabled) {
// POSIX named classes are not supported, use alternative a-zA-Z0-9 match
$pattern = ‘/[^a-zA-Z0-9’ . $whiteSpace . ‘_\-]/’;
} else if (self::$_meansEnglishAlphabet) {
//The Alphabet means english alphabet.
$pattern = ‘/[^a-zA-Z0-9’ . $whiteSpace . ‘_\-]/u’;
} else {
//The Alphabet means each language’s alphabet.
$pattern = ‘/[^\p{L}\p{N}’ . $whiteSpace . ‘_\-]/u’;
}return preg_replace($pattern, ”, (string) $value);
}
}
The file should be placed under /library/My/Filter/AlnumD.php
Calling:
$filteralnumD = new Zend_Filter ( );
$filteralnumD->addFilter ( new My_Filter_AlnumD(1)); //1 to leave whitespaces
$vartoClean=$filteralnumD->filter($this->_getParam ( ‘getVar’));