Zend Framework Filter Zend_filter usage Detailed _php example

Source: Internet
Author: User
Tags constructor numeric lowercase php programming posix zend zend framework

The examples in this article describe the Zend_filter usage of the Zend Framework filter. Share to everyone for your reference, specific as follows:

Introduction: The filter is the process of filtering the input, clearing the content that does not conform to the filtering rules, and returning the remainder .

A zend_filter component is used in Zend to implement filtering. There is a zend_filter_interface subclass that provides an interface for implementing a generic filter.

To implement a filter class, you need to implement a method named Filter () in the interface.

The following example shows how to use the filters defined in Zend_filter, which demonstrates how to implement the function of lowercase letters.

Code:

<?php
require_once ' zend/filter/stringtolower.php ';  Load Subclass
$filter = new Zend_filter_stringtolower;    Instantiate object
$temp 1 = "ABCDEFGH";              Define the content to be filtered
$temp 2 = "I love nan Jing";
echo "Content:". $temp 1. " <p> after filtration for: ";
echo $filter->filter ($temp 1);
echo "<p>";
echo "Content:". $temp 2. " <p> after filtration for: ";
echo $filter->filter ($temp 2);

Results:

Content: ABCDEFGH
After filtration: ABCDEFGH
Content: I love nan Jing
Filtered for: I love Nan Jing

Why is it so magical? I want to explore the structure of the interior! Here's a look at how it works inside.

Class Zend_filter_stringtolower implements Zend_filter_interface {/** * Encoding for the input string * * @va
  R String */protected $_encoding = NULL; /** * Constructor * * * @param string|array| Zend_config $options OPTIONAL */Public function __construct ($options = null) {if ($options instanceof Zend_co
    Nfig) {$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 [' en
    Coding '] = mb_internal_encoding ();
    } if (array_key_exists (' encoding ', $options)) {$this->setencoding ($options [' Encoding ']); }/** * Returns the SET encoding * * @return String */Public Function getencoding () {return $t his->_encoding; /** * Set The input encoding for the given string * * @param string $encoding * @return zend_filter_string ToLower provides a fluent interface * @throws zend_filter_exception */Public Function setencoding ($encoding = nul L) {if ($encoding!== null) {if (!function_exists (' Mb_strtolower ')) {require_once ' Zend/filter/exce
        Ption.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/ex
        Ception.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 n Ecessary * * @param string $value
   * @return String */Public Function filter ($value) {if ($this->_encoding!== null) {return Mb_st
    Rtolower ((String) $value, $this->_encoding);
  Return Strtolower ((string) $value);

 }
}

Study:

The source code meaning is probably to implement the Zend_filter_interface interface first.

Defines a private variable $_encoding, the initial value is null, and the general private variable begins with an _ underscore.

The constructor is then used to initialize the work and set the encoding.

As for this encoing attribute is used, I am not very clear, anyway, for it, the source code wrote a lot.

There are three methods in the class, one is setencoding, the other is getencoding, a main function of filter. There are two ways to write for encoding.

You can use the Setencoding method directly in the constructor using $this->setencoding (). You can set the private property to a good value.

Then choose what method to use to make the letter lowercase, based on the contents of the private property.

I go, this kind of thinking is really a lot of things. In fact, the core code is the two sentences, Strtolower ((String) $value).

This class is cool, I've never used private properties. The question is also not as comprehensive as the author, all kinds of validation, various circumstances considered. Like what

You can see from the constructor that he considers the comprehensiveness of the problem.

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 worth admiring.

Next, the filter chain, which is the role of multiple filters in tandem together with the use. A filter chain is a connection to multiple filters. When the specified content is filtered, the

Each filter will be filtered or transformed in its order. When all the filtering operations have been performed, the filter chain returns the final filter result.

That sounds interesting!

What is the specific implementation step?

You first instantiate an object for Class Zend_filter, and then add a filter to the filter chain through the instance's AddFilter () method.

The following example demonstrates how to use a filter chain to filter and transform data multiple.

Code:

<?php
require_once ' zend/filter.php ';         Loading Zend_filter class
require_once ' zend/filter/alpha.php ';      Loading the 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 filter to filter chain
$temp 1 = "12345ASDF67ASDFASDF";
$temp 2 = "#$%^! @fffff";
$temp 3 = "Welcome to Bei Jing";
echo "Content:". $temp 1. " <p> after filtration for: ";
echo $filterChain->filter ($temp 1);
echo "<p>";
echo "Content:". $temp 2. " <p> after filtration for: ";
echo $filterChain->filter ($temp 2);
echo "<p>";
echo "Content:". $temp 3. " <p> after filtration for: ";
echo $filterChain->filter ($temp 3);
echo "<p>";

Results:

Content: 12345ASDF67ASDFASDF
After filtration: ASDFASDFASDF
Content: #$%^! @fffff
After filtration: FFFFF
Content: Welcome to Bei Jing
After filtration: WELCOME to BEI JING

Analysis:

Alpha is very powerful here, filtering numbers and special characters, and even spaces are filtered. Fortunately, I initialized with the addition of a parameter "", so that the space retained.

Why is it so magical?

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 中文版 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, if not letters or spaces, all removed. The PHP method used is preg_replace. In addition, regular expressions are used. [^a-za-z] represents other characters that are otherwise.

The $whitespace member property here is set at initialization time, 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 ', ' en ')
      ;
    }
}

In addition, there are two ways to set whether to allow spaces and to get whether to set the allowed spaces.

/**
* 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 parsing, we seem to know more about its construction, that is, using regular filtering. The property Allowwhitespace is also used to control whether spaces are filtered.

I've just introduced two filters, one is Stringtoupper, the other is Alpha, and here are some other filters.

The first is Alnum, which filters both Non-numeric and non-alphanumeric content, and executes the filter () method, which returns the contents of pure numbers and letters, which is the set of Zend_filter_alpha (filtered non-alphabetic) and zend_filter_digits (filtered non-numeric).

The concrete example will not lift, all the same.

Let's look at the structure inside it,

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 中文版 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);
}

Through the regular filter, except for the letter and the number of content.

The next exit is the Htmlentities HTML filter.

Code:

<?php
require_once ' zend/filter/htmlentities.php ';
$filter = new Zend_filter_htmlentities ();
$temp 1 = "aaa</button>";
$temp 3 = " 
 

Results:

With the results, we can see that it restores the HTML content to the original code. Because the filter is an encapsulation of the function htmlentities, follow the rules for that function. "<" and ">" will be converted to "<" and ">" respectively, after this conversion,

The corresponding HTML content becomes the string that is displayed in its original format.

More interested in Zend related content readers can view the site topics: "The introduction of the Zend Framework frame", "PHP Excellent Development Framework Summary", "Yii framework Introduction and common skills Summary", "thinkphp Introductory Course", "PHP object-oriented Programming Program , "Php+mysql Database operation Introduction Tutorial" and "PHP common database Operation Skills Summary"

I hope this article will help you with your PHP programming based on the Zend Framework.

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.