当前位置:Gxlcms > php框架 > Zend Framework过滤器Zend_Filter用法详解

Zend Framework过滤器Zend_Filter用法详解

时间:2021-07-01 10:21:17 帮助过:5人阅读

本文实例讲述了Zend Framework过滤器Zend_Filter用法。分享给大家供大家参考,具体如下:

引言:过滤器是对输入内容进行过滤,清除其中不符合过滤规则的内容,并将其余内容返回的过程

Zend中有个Zend_Filter组件用来实现过滤的功能。其中有个Zend_Filter_Interface子类,该子类为实现一般过滤器提供了接口。

要实现过滤器类,需要实现该接口中一个名为filter()的方法。

下面通过实例来演示如何使用Zend_Filter中定义的过滤器,该例演示如何实现字母转小写的功能。

代码:

  1. <?php
  2. require_once 'Zend/Filter/StringToLower.php'; //加载子类
  3. $filter = new Zend_Filter_StringToLower; //实例化对象
  4. $temp1 = "ABCDefGH"; //定义待过滤内容
  5. $temp2 = "我爱Nan Jing";
  6. echo "内容:".$temp1."<p>经过滤后为:";
  7. echo $filter->filter($temp1);
  8. echo "<p>";
  9. echo "内容:".$temp2."<p>经过滤后为:";
  10. echo $filter->filter($temp2);

结果:

内容:ABCDefGH
经过滤后为:abcdefgh
内容:我爱Nan Jing
经过滤后为:我爱nan jing

为什么如此神奇呢?不禁让我想探索一下其内部的构造!下面来研读一下其内部的工作原理。

  1. class Zend_Filter_StringToLower implements Zend_Filter_Interface
  2. {
  3. /**
  4. * Encoding for the input string
  5. *
  6. * @var string
  7. */
  8. protected $_encoding = null;
  9. /**
  10. * Constructor
  11. *
  12. * @param string|array|Zend_Config $options OPTIONAL
  13. */
  14. public function __construct($options = null)
  15. {
  16. if ($options instanceof Zend_Config) {
  17. $options = $options->toArray();
  18. } else if (!is_array($options)) {
  19. $options = func_get_args();
  20. $temp = array();
  21. if (!empty($options)) {
  22. $temp['encoding'] = array_shift($options);
  23. }
  24. $options = $temp;
  25. }
  26. if (!array_key_exists('encoding', $options) && function_exists('mb_internal_encoding')) {
  27. $options['encoding'] = mb_internal_encoding();
  28. }
  29. if (array_key_exists('encoding', $options)) {
  30. $this->setEncoding($options['encoding']);
  31. }
  32. }
  33. /**
  34. * Returns the set encoding
  35. *
  36. * @return string
  37. */
  38. public function getEncoding()
  39. {
  40. return $this->_encoding;
  41. }
  42. /**
  43. * Set the input encoding for the given string
  44. *
  45. * @param string $encoding
  46. * @return Zend_Filter_StringToLower Provides a fluent interface
  47. * @throws Zend_Filter_Exception
  48. */
  49. public function setEncoding($encoding = null)
  50. {
  51. if ($encoding !== null) {
  52. if (!function_exists('mb_strtolower')) {
  53. require_once 'Zend/Filter/Exception.php';
  54. throw new Zend_Filter_Exception('mbstring is required for this feature');
  55. }
  56. $encoding = (string) $encoding;
  57. if (!in_array(strtolower($encoding), array_map('strtolower', mb_list_encodings()))) {
  58. require_once 'Zend/Filter/Exception.php';
  59. throw new Zend_Filter_Exception("The given encoding '$encoding' is not supported by mbstring");
  60. }
  61. }
  62. $this->_encoding = $encoding;
  63. return $this;
  64. }
  65. /**
  66. * Defined by Zend_Filter_Interface
  67. *
  68. * Returns the string $value, converting characters to lowercase as necessary
  69. *
  70. * @param string $value
  71. * @return string
  72. */
  73. public function filter($value)
  74. {
  75. if ($this->_encoding !== null) {
  76. return mb_strtolower((string) $value, $this->_encoding);
  77. }
  78. return strtolower((string) $value);
  79. }
  80. }

研读:

源代码意思大概是先实现Zend_Filter_Interface接口。

定义一个私有变量$_encoding,初始值为null,一般私有变量都是以_下划线开头。

然后通过构造函数进行初始化工作,设置encoding。

至于这个encoing属性是作何用的,我就不大清楚了,反正为了它,源码写了不少代码。

类中有三个方法,一个是setEncoding,一个是getEncoding,一个主要功能的filter。有两个方法都是为了encoding来写的。

在构造函数中使用setEncoding方法直接用$this->setEncoding()就可。就可以把私有属性设置好值了。

然后根据私有属性的内容来选择使用什么方法来使得字母变小写。

我去,这个类考虑的东西还真够多的。其实核心代码就那两句,strtolower((string) $value)。

这个类很酷,我从来没用过私有属性。考虑问题也没有作者那么全面,各种验证,各种情况考虑。比如,

从构造函数中就可以看出他考虑问题的全面性。

  1. if ($options instanceof Zend_Config) {
  2. $options = $options->toArray();
  3. } else if (!is_array($options)) {
  4. $options = func_get_args();
  5. $temp = array();
  6. if (!empty($options)) {
  7. $temp['encoding'] = array_shift($options);
  8. }
  9. $options = $temp;
  10. }
  11. if (!array_key_exists('encoding', $options) && function_exists('mb_internal_encoding')) {
  12. $options['encoding'] = mb_internal_encoding();
  13. }
  14. if (array_key_exists('encoding', $options)) {
  15. $this->setEncoding($options['encoding']);
  16. }

总的来说还是值得佩服的。

下面谈谈过滤器链,它的作用是将多个过滤器串联起来配合使用。过滤器链就是多个过滤器的一个连接。在对指定的内容进行过滤时,

每个过滤器将按照其顺序分别进行过滤或者转化操作。当所有的过滤操作都执行完毕时,过滤器链返回最终的过滤结果。

听起来蛮有趣的啊!

具体实现步骤是什么呢?

首先要为类Zend_Filter实例化一个对象,然后通过该实例的addFilter()方法向过滤器链中添加过滤器。

下面通过示例演示如何使用过滤器链对数据进行多重过滤及转化。

代码:

  1. <?php
  2. require_once 'Zend/Filter.php'; //加载Zend_Filter类
  3. require_once 'Zend/Filter/Alpha.php'; //加载Zend_Filter_Alpha子类
  4. require_once 'Zend/Filter/StringToUpper.php'; //加载Zend_Filter_StringToUpper子类
  5. $filterChain = new Zend_Filter(); //创建过滤器链
  6. $filterChain ->addFilter(new Zend_Filter_Alpha(" "))
  7. ->addFilter(new Zend_Filter_StringToUpper());//向过滤器链中添加过滤器
  8. $temp1 = "12345asdf67asdfasdf";
  9. $temp2 = "#$%^!@fffff";
  10. $temp3 = "Welcome to Bei Jing";
  11. echo "内容:".$temp1."<p>经过过滤后为:";
  12. echo $filterChain->filter($temp1);
  13. echo "<p>";
  14. echo "内容:".$temp2."<p>经过过滤后为:";
  15. echo $filterChain->filter($temp2);
  16. echo "<p>";
  17. echo "内容:".$temp3."<p>经过过滤后为:";
  18. echo $filterChain->filter($temp3);
  19. echo "<p>";

结果:

内容:12345asdf67asdfasdf
经过过滤后为:ASDFASDFASDF
内容:#$%^!@fffff
经过过滤后为:FFFFF
内容:Welcome to Bei Jing
经过过滤后为:WELCOME TO BEI JING

分析:

这里的Alpha很强大啊,过滤数字和特殊字符,连空格都能过滤。还好我初始化的时候加了个参数" ",才使得空格保留了下来。

为何如此神奇呢?

核心代码就这一块

  1. public function filter($value)
  2. {
  3. $whiteSpace = $this->allowWhiteSpace ? '\s' : '';
  4. if (!self::$_unicodeEnabled) {
  5. // POSIX named classes are not supported, use alternative a-zA-Z match
  6. $pattern = '/[^a-zA-Z' . $whiteSpace . ']/';
  7. } else if (self::$_meansEnglishAlphabet) {
  8. //The Alphabet means english alphabet.
  9. $pattern = '/[^a-zA-Z' . $whiteSpace . ']/u';
  10. } else {
  11. //The Alphabet means each language's alphabet.
  12. $pattern = '/[^\p{L}' . $whiteSpace . ']/u';
  13. }
  14. return preg_replace($pattern, '', (string) $value);
  15. }

分析:这里对内容进行过滤,如果不是字母或者空格,就统统去掉。用到的php方法是preg_replace。此外,还用到了正则表达式。[^a-zA-Z]表示除此之外的其他字符。

这里的$whiteSpace成员属性,是初始化的时候设置的,具体代码如下:

  1. public function __construct($allowWhiteSpace = false)
  2. {
  3. if ($allowWhiteSpace instanceof Zend_Config) {
  4. $allowWhiteSpace = $allowWhiteSpace->toArray();
  5. } else if (is_array($allowWhiteSpace)) {
  6. if (array_key_exists('allowwhitespace', $allowWhiteSpace)) {
  7. $allowWhiteSpace = $allowWhiteSpace['allowwhitespace'];
  8. } else {
  9. $allowWhiteSpace = false;
  10. }
  11. }
  12. $this->allowWhiteSpace = (boolean) $allowWhiteSpace;
  13. if (null === self::$_unicodeEnabled) {
  14. self::$_unicodeEnabled = (@preg_match('/\pL/u', 'a')) ? true : false;
  15. }
  16. if (null === self::$_meansEnglishAlphabet) {
  17. $this->_locale = new Zend_Locale('auto');
  18. self::$_meansEnglishAlphabet = in_array($this->_locale->getLanguage(),
  19. array('ja', 'ko', 'zh')
  20. );
  21. }
  22. }

此外,还有两个方法来设置是否允许有空格和获取是否设置了允许空格。

  1. /**
  2. * Returns the allowWhiteSpace option
  3. *
  4. * @return boolean
  5. */
  6. public function getAllowWhiteSpace()
  7. {
  8. return $this->allowWhiteSpace;
  9. }
  10. /**
  11. * Sets the allowWhiteSpace option
  12. *
  13. * @param boolean $allowWhiteSpace
  14. * @return Zend_Filter_Alpha Provides a fluent interface
  15. */
  16. public function setAllowWhiteSpace($allowWhiteSpace)
  17. {
  18. $this->allowWhiteSpace = (boolean) $allowWhiteSpace;
  19. return $this;
  20. }

剖析完之后,我们似乎就更了解它的构造了,就是使用正则过滤而已。同时通过属性allowWhiteSpace来控制是否过滤空格。

刚才介绍了两种过滤器,一个是StringToUpper,一个是Alpha,下面再介绍其它的一些过滤器。

首先是Alnum,过滤非数字和非字母的内容,执行filter()方法,将返回纯数字与字母的内容,它是Zend_Filter_Alpha(过滤非字母)与Zend_Filter_Digits(过滤非数值)的并集。

具体的例子就不举了,都差不多。

我们来看看它内部的构造,

  1. public function filter($value)
  2. {
  3. $whiteSpace = $this->allowWhiteSpace ? '\s' : '';
  4. if (!self::$_unicodeEnabled) {
  5. // POSIX named classes are not supported, use alternative a-zA-Z0-9 match
  6. $pattern = '/[^a-zA-Z0-9' . $whiteSpace . ']/';
  7. } else if (self::$_meansEnglishAlphabet) {
  8. //The Alphabet means english alphabet.
  9. $pattern = '/[^a-zA-Z0-9' . $whiteSpace . ']/u';
  10. } else {
  11. //The Alphabet means each language's alphabet.
  12. $pattern = '/[^\p{L}\p{N}' . $whiteSpace . ']/u';
  13. }
  14. return preg_replace($pattern, '', (string) $value);
  15. }

通过正则过滤除字母和数字之外的内容。

下面出场的是HtmlEntities HTML过滤器。

代码:

  1. <?php
  2. require_once 'Zend/Filter/Htmlentities.php';
  3. $filter = new Zend_Filter_HtmlEntities();
  4. $temp1 = "<img src = './1.png' width='100px'>";
  5. $temp2 = "<button>aaa</button>";
  6. $temp3 = "<h1>Welcome to Bei Jing</h1>";
  7. echo "内容:".$temp1."<p>经过过滤为:";
  8. echo $filter->filter($temp1);
  9. echo "<p>";
  10. echo "内容:".$temp2."<p>经过过滤为:";
  11. echo $filter->filter($temp2);
  12. echo "<p>";
  13. echo "内容:".$temp3."<p>经过过滤为:";
  14. echo $filter->filter($temp3);
  15. echo "<p>";

结果:

通过结果,我们看出它将html内容还原成原始代码了。由于该过滤器是对函数htmlentities进行的封装,所以遵循该函数的规则。即将“<”与“>”分别转换为“<”与“>”,经过这样的转换,

相应的HTML内容就变成了以其原始格式显示的字符串。

更多关于zend相关内容感兴趣的读者可查看本站专题:《Zend FrameWork框架入门教程》、《php优秀开发框架总结》、《Yii框架入门及常用技巧总结》、《ThinkPHP入门教程》、《php面向对象程序设计入门教程》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》

希望本文所述对大家基于Zend Framework框架的PHP程序设计有所帮助。

人气教程排行