搜尋
首頁php教程PHP开发Zend Framework過濾器Zend_Filter用法詳解

本文實例講述了Zend Framework過濾器Zend_Filter用法。分享給大家供大家參考,具體如下:

引言:過濾器是對輸入內容進行過濾,清除其中不符合過濾規則的內容,並將其餘內容返回的過程。

Zend中有個Zend_Filter元件用來實現過濾的功能。其中有個Zend_Filter_Interface子類,該子類為實作一般過濾器提供了介面。

要實作過濾器類,需要實作該介面中一個名為filter()的方法。

下面透過實例來示範如何使用Zend_Filter中定義的篩選器,該範例示範如何實作字母轉小寫的功能。

代碼:

<?php
require_once &#39;Zend/Filter/StringToLower.php&#39;;  //加载子类
$filter = new Zend_Filter_StringToLower;    //实例化对象
$temp1 = "ABCDefGH";              //定义待过滤内容
$temp2 = "我爱Nan Jing";
echo "内容:".$temp1."<p>经过滤后为:";
echo $filter->filter($temp1);
echo "<p>";
echo "内容:".$temp2."<p>经过滤后为:";
echo $filter->filter($temp2);

   

結果:

內容:ABCDefGH
過濾後為:abcdefgh
內容:我愛Nan Jnan Jan J30303000ing不禁讓我想探索一下其內部的構造!下面來研讀一下其內部的工作原理。

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[&#39;encoding&#39;] = array_shift($options);
      }
      $options = $temp;
    }
    if (!array_key_exists(&#39;encoding&#39;, $options) && function_exists(&#39;mb_internal_encoding&#39;)) {
      $options[&#39;encoding&#39;] = mb_internal_encoding();
    }
    if (array_key_exists(&#39;encoding&#39;, $options)) {
      $this->setEncoding($options[&#39;encoding&#39;]);
    }
  }
  /**
   * 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(&#39;mb_strtolower&#39;)) {
        require_once &#39;Zend/Filter/Exception.php&#39;;
        throw new Zend_Filter_Exception(&#39;mbstring is required for this feature&#39;);
      }
      $encoding = (string) $encoding;
      if (!in_array(strtolower($encoding), array_map(&#39;strtolower&#39;, mb_list_encodings()))) {
        require_once &#39;Zend/Filter/Exception.php&#39;;
        throw new Zend_Filter_Exception("The given encoding &#39;$encoding&#39; 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);
  }
}

   

研讀:

原始碼意思大概是先實作Zend_Filter_Interface介面。

定義一個私有變數$_encoding,初始值為null,一般私有變數都是以_底線開頭。

然後透過建構函式進行初始化工作,設定encoding。

至於這個encoing屬性是作何用的,我就不大清楚了,反正為了它,源碼寫了不少代碼。

類別中有三個方法,一個是setEncoding,一個是getEncoding,一個主要功能的filter。有兩個方法都是為了encoding來寫的。

在建構函式中使用setEncoding方法直接用$this->setEncoding()就可。就可以把私有屬性設定好值了。

然後根據私有屬性的內容來選擇使用什麼方法來使得字母變小寫。

我去,這個類別考慮的東西還真夠多的。其實核心程式碼就那兩句,strtolower((string) $value)。

這個類別很酷,我從來沒用過私有屬性。考慮問題也沒有作者那麼全面,各種驗證,各種情況考量。例如,

從構造函數中就可以看出他考慮問題的全面性。

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

   

總的來說還是值得佩服的。

下面談談過濾器鏈,它的作用是將多個過濾器串聯起來配合使用。過濾器鏈就是多個過濾器的一個連接。在對指定的內容進行過濾時,

每個過濾器將按照其順序分別進行過濾或轉換操作。當所有的過濾操作都執行完畢時,過濾器鏈會傳回最終的過濾結果。

聽起來蠻有趣的啊!

具體實現步驟是什麼?

首先要為類別Zend_Filter實例化一個對象,然後透過該實例的addFilter()方法向過濾器鏈中添加過濾器。

下面透過範例示範如何使用過濾器鏈對資料進行多重過濾及轉換。

代碼:

<?php
require_once &#39;Zend/Filter.php&#39;;         //加载Zend_Filter类
require_once &#39;Zend/Filter/Alpha.php&#39;;      //加载Zend_Filter_Alpha子类
require_once &#39;Zend/Filter/StringToUpper.php&#39;;  //加载Zend_Filter_StringToUpper子类
$filterChain = new Zend_Filter();        //创建过滤器链
$filterChain ->addFilter(new Zend_Filter_Alpha(" "))
  ->addFilter(new Zend_Filter_StringToUpper());//向过滤器链中添加过滤器
$temp1 = "12345asdf67asdfasdf";
$temp2 = "#$%^!@fffff";
$temp3 = "Welcome to Bei Jing";
echo "内容:".$temp1."<p>经过过滤后为:";
echo $filterChain->filter($temp1);
echo "<p>";
echo "内容:".$temp2."<p>经过过滤后为:";
echo $filterChain->filter($temp2);
echo "<p>";
echo "内容:".$temp3."<p>经过过滤后为:";
echo $filterChain->filter($temp3);
echo "<p>";

   

結果:

內容:12345asdf67asdfasdf

經過濾後為:ASDFASDFASDF2345asdf67asdfasdf

分Jing

過濾後為:WELCOME TO BEI JING

分析:

這裡的Alpha很強大啊,過濾數字和特殊字符,連空格都能過濾。還好我初始化的時候加了個參數" ",才使得空格保留了下來。

為何如此神奇呢?

核心程式碼就這一片

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

   

分析:這裡將內容過濾,如果不是字母或空格,就統統去掉。用到的php方法是preg_replace。此外,還用到了正規表示式。 [^a-zA-Z]表示除此之外的其他字元。

這裡的$whiteSpace成員屬性,是初始化的時候設定的,具體程式碼如下:

public function __construct($allowWhiteSpace = false)
{
    if ($allowWhiteSpace instanceof Zend_Config) {
      $allowWhiteSpace = $allowWhiteSpace->toArray();
    } else if (is_array($allowWhiteSpace)) {
      if (array_key_exists(&#39;allowwhitespace&#39;, $allowWhiteSpace)) {
        $allowWhiteSpace = $allowWhiteSpace[&#39;allowwhitespace&#39;];
      } else {
        $allowWhiteSpace = false;
      }
    }
    $this->allowWhiteSpace = (boolean) $allowWhiteSpace;
    if (null === self::$_unicodeEnabled) {
      self::$_unicodeEnabled = (@preg_match(&#39;/\pL/u&#39;, &#39;a&#39;)) ? true : false;
    }
    if (null === self::$_meansEnglishAlphabet) {
      $this->_locale = new Zend_Locale(&#39;auto&#39;);
      self::$_meansEnglishAlphabet = in_array($this->_locale->getLanguage(),
      array(&#39;ja&#39;, &#39;ko&#39;, &#39;zh&#39;)
      );
    }
}

   

此外,還有兩個方法來設定是否允許有空格和取得是否設定了允許空格。

/**
* 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;
}

   

剖析完之後,我們似乎就更了解它的構造了,就是使用正規過濾而已。同時透過屬性allowWhiteSpace來控制是否過濾空格。

剛才介紹了兩種過濾器,一個是StringToUpper,一個是Alpha,下面再介紹其它的一些過濾器。

首先是Alnum,過濾非數字和非字母的內容,執行filter()方法,將傳回純數字與字母的內容,它是Zend_Filter_Alpha(過濾非字母)與Zend_Filter_Digits(過濾非數值)的並集。

具體的例子就不舉了,都差不多。

我們來看看它內部的構造,

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

   

透過正則過濾除字母和數字之外的內容。

下面出場的是HtmlEntities HTML過濾器。

代碼:

<?php
require_once &#39;Zend/Filter/Htmlentities.php&#39;;
$filter = new Zend_Filter_HtmlEntities();
$temp1 = "<img  src = &#39;./1.png&#39;    style="max-width:90%"Zend Framework過濾器Zend_Filter用法詳解" >";
$temp2 = "<button>aaa</button>";
$temp3 = "<h1 id="Welcome-nbsp-to-nbsp-Bei-nbsp-Jing">Welcome to Bei Jing</h1>";
echo "内容:".$temp1."<p>经过过滤为:";
echo $filter->filter($temp1);
echo "<p>";
echo "内容:".$temp2."<p>经过过滤为:";
echo $filter->filter($temp2);
echo "<p>";
echo "内容:".$temp3."<p>经过过滤为:";
echo $filter->filter($temp3);
echo "<p>";

   

結果:

透過結果,我們看出它將html內容還原成原始程式碼了。由於該過濾器是對函數htmlentities進行的封裝,所以遵循該函數的規則。即將“”分別轉換為“”,經過這樣的轉換,

對應的HTML內容變成了以其原始格式顯示的字串。

希望本文所述對大家基於Zend Framework框架的PHP程式設計有所幫助。

更多Zend Framework過濾器Zend_Filter用法詳解相關文章請關注PHP中文網!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

WebStorm Mac版

WebStorm Mac版

好用的JavaScript開發工具

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器