Zend Framework filter Zend_Filter Usage Details, zendzend_filter

Source: Internet
Author: User
Tags zend framework

Zend Framework filter Zend_Filter Usage Details, zendzend_filter

This article describes the Zend_Filter usage of the Zend Framework filter. We will share this with you for your reference. The details are as follows:

Introduction:Filters filter the input content, clear the content that does not comply with the filter rules, and return other content.

Zend has a Zend_Filter component for filtering. There is a Zend_Filter_Interface subclass that provides an interface for implementing General filters.

To implement the filter class, you must implement a method named filter () in this interface.

The following example shows how to use the filter defined in Zend_Filter. This example shows how to convert letters to lowercase letters.

Code:

<? Phprequire_once 'zend/Filter/StringToLower. php '; // load subclass $ filter = new Zend_Filter_StringToLower; // instantiate the object $ temp1 = "ABCDefGH"; // define the content to be filtered $ temp2 = "I love Nan Jing "; echo "content :". $ temp1. "<p> after filtering:"; echo $ filter-> filter ($ temp1); echo "<p>"; echo "content :". $ temp2. "<p> after filtering:"; echo $ filter-> filter ($ temp2 );

Result:

Content: ABCDefGH
After filtering: abcdefgh
Content: I love Nan Jing.
Filtered: I love nan jing

Why is it so amazing? I cannot help but want to explore its internal structure! Next, let's take a look at its internal working principles.

class Zend_Filter_StringToLower implements Zend_Filter_Interface{  /**   * Encoding for the input string   *   * @var string   */  protected $_encoding = null;  /**   * Constructor   *   * @param string|array|Zend_Config $options OPTIONAL   */  public function __construct($options = null)  {    if ($options instanceof Zend_Config) {      $options = $options->toArray();    } else if (!is_array($options)) {      $options = func_get_args();      $temp  = array();      if (!empty($options)) {        $temp['encoding'] = array_shift($options);      }      $options = $temp;    }    if (!array_key_exists('encoding', $options) && function_exists('mb_internal_encoding')) {      $options['encoding'] = mb_internal_encoding();    }    if (array_key_exists('encoding', $options)) {      $this->setEncoding($options['encoding']);    }  }  /**   * Returns the set encoding   *   * @return string   */  public function getEncoding()  {    return $this->_encoding;  }  /**   * Set the input encoding for the given string   *   * @param string $encoding   * @return Zend_Filter_StringToLower Provides a fluent interface   * @throws Zend_Filter_Exception   */  public function setEncoding($encoding = null)  {    if ($encoding !== null) {      if (!function_exists('mb_strtolower')) {        require_once 'Zend/Filter/Exception.php';        throw new Zend_Filter_Exception('mbstring is required for this feature');      }      $encoding = (string) $encoding;      if (!in_array(strtolower($encoding), array_map('strtolower', mb_list_encodings()))) {        require_once 'Zend/Filter/Exception.php';        throw new Zend_Filter_Exception("The given encoding '$encoding' is not supported by mbstring");      }    }    $this->_encoding = $encoding;    return $this;  }  /**   * Defined by Zend_Filter_Interface   *   * Returns the string $value, converting characters to lowercase as necessary   *   * @param string $value   * @return string   */  public function filter($value)  {    if ($this->_encoding !== null) {      return mb_strtolower((string) $value, $this->_encoding);    }    return strtolower((string) $value);  }}

Study:

The source code indicates implementing the Zend_Filter_Interface interface first.

Defines a private variable $ _ encoding. The initial value is null. Generally, all private variables start with _ underline.

Then perform initialization through the constructor and set encoding.

I don't know how to use this encoing attribute. I wrote a lot of code for the source code.

There are three methods in the class: setEncoding, getEncoding, and filter. Two methods are written for encoding.

Use the setEncoding method in the constructor to directly use $ this-> setEncoding. You can set the private property value.

Then, based on the content of the private attribute, select the method to make the letter smaller and write.

I went there and thought about enough things for this class. Actually, the core code is the strtolower (string) $ value ).

This class is cool. I have never used private attributes. The problem was not as comprehensive as the author was. Various verifications and situations were considered. For example,

It can be seen from the constructor that the problem is comprehensive.

if ($options instanceof Zend_Config) {  $options = $options->toArray();} else if (!is_array($options)) {  $options = func_get_args();  $temp  = array();  if (!empty($options)) {    $temp['encoding'] = array_shift($options);  }  $options = $temp;}if (!array_key_exists('encoding', $options) && function_exists('mb_internal_encoding')) {  $options['encoding'] = mb_internal_encoding();}if (array_key_exists('encoding', $options)) {  $this->setEncoding($options['encoding']);}

In general, it is admirable.

Next we will talk about the filter chain. Its function is to concatenate multiple filters for use. A filter chain is a connection of multiple filters. When filtering the specified content,

Each filter is filtered or converted separately in the order. When all the filtering operations are completed, the filter chain returns the final filtering result.

It sounds interesting!

What are the specific implementation steps?

First, you need to instantiate an object for the class Zend_Filter, and then add a filter to the filter chain through the addFilter () method of the instance.

The following example shows how to use the filter chain to filter and convert data in multiple ways.

Code:

<? Phprequire_once 'zend/Filter. php '; // load Zend_Filter class require_once' Zend/Filter/Alpha. php '; // load Zend_Filter_Alpha subclass require_once' Zend/Filter/StringToUpper. php '; // load Zend_Filter_StringToUpper subclass $ filterChain = new Zend_Filter (); // create a filter chain $ filterChain-> addFilter (new Zend_Filter_Alpha ("")) -> addFilter (new Zend_Filter_StringToUpper (); // Add a filter to the filter chain $ temp1 = "12345asdf67asdfasdf"; $ temp2 = "# $ % ^! @ Fffff "; $ temp3 =" Welcome to Bei Jing "; echo" content :". $ temp1. "<p> after filtering:"; echo $ filterChain-> filter ($ temp1); echo "<p>"; echo "content :". $ temp2. "<p> after filtering:"; echo $ filterChain-> filter ($ temp2); echo "<p>"; echo "content :". $ temp3. "<p> after filtering:"; echo $ filterChain-> filter ($ temp3); echo "<p> ";

Result:

Content: 12345asdf67asdfasdf
After filtering: ASDFASDFASDF
Content: # $ % ^! @ Fffff
After filtering: FFFFF
Content: Welcome to Bei Jing
The filtered result is: welcome to bei jing.

Analysis:

The Alpha here is very powerful. It can be used to filter numbers and special characters with spaces. Fortunately, I added a parameter "" during initialization to save the space.

Why is it so amazing?

This is the core code.

public function filter($value){    $whiteSpace = $this->allowWhiteSpace ? '\s' : '';    if (!self::$_unicodeEnabled) {      // POSIX named classes are not supported, use alternative a-zA-Z match      $pattern = '/[^a-zA-Z' . $whiteSpace . ']/';    } else if (self::$_meansEnglishAlphabet) {      //The Alphabet means english alphabet.      $pattern = '/[^a-zA-Z' . $whiteSpace . ']/u';    } else {      //The Alphabet means each language's alphabet.      $pattern = '/[^\p{L}' . $whiteSpace . ']/u';    }    return preg_replace($pattern, '', (string) $value);}

Analysis:Here, the content is filtered out. If it is not a letter or space, it will be removed. The php method used is preg_replace. In addition, regular expressions are used. [^ A-zA-Z] indicates other characters.

The $ whiteSpace member attribute is set during initialization. The Code is as follows:

public function __construct($allowWhiteSpace = false){    if ($allowWhiteSpace instanceof Zend_Config) {      $allowWhiteSpace = $allowWhiteSpace->toArray();    } else if (is_array($allowWhiteSpace)) {      if (array_key_exists('allowwhitespace', $allowWhiteSpace)) {        $allowWhiteSpace = $allowWhiteSpace['allowwhitespace'];      } else {        $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')      );    }}

In addition, there are two ways to set whether spaces are allowed or not.

/*** Returns the allowWhiteSpace option** @return boolean*/public function getAllowWhiteSpace(){    return $this->allowWhiteSpace;}/*** Sets the allowWhiteSpace option** @param boolean $allowWhiteSpace* @return Zend_Filter_Alpha Provides a fluent interface*/public function setAllowWhiteSpace($allowWhiteSpace){    $this->allowWhiteSpace = (boolean) $allowWhiteSpace;    return $this;}

After the analysis, we seem to have a better understanding of its structure, that is, using regular expression filtering. Meanwhile, the allowWhiteSpace attribute is used to control whether to filter spaces.

We have introduced two filters, StringToUpper and Alpha. Next we will introduce some other filters.

First, Alnum is used to filter non-numbers and non-letter content. The filter () method returns the content of pure numbers and letters. It is Zend_Filter_Alpha (Filtering non-letters) the Union of Zend_Filter_Digits (Filtering non-numeric values.

The specific examples will not be mentioned, and they will all be similar.

Let's take a look at its internal structure,

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);}

Use regular expressions to filter content except letters and numbers.

The following figure shows the HtmlEntities HTML filter.

Code:

<? Phprequire_once 'zend/Filter/Htmlentities. php '; $ filter = new Zend_Filter_HtmlEntities (); $ temp1 = " "; $ temp2 =" <button> aaa </button> "; $ temp3 = "

Result:

The result shows that the html content is restored to the original code. This filter encapsulates the htmlentities function, so it follows the rules of this function. Convert "<" and ">" to "<" and ">" respectively,

The corresponding HTML content becomes a string displayed in its original format.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.