Zend Framework学习之Zend_Filter_StripTags
Strip Tags HTML字符过滤器与Zend_Filter_HtmlEntities过滤器不同,
后者只是将“<”、“>”符号进行转换。而Zend_Filter_StripTags过滤器则是直接过滤掉“<>”符号所包含的内容。
案例:
<?php require_once 'Zend/Filter/StripTags.php'; $filter = new Zend_Filter_StripTags(); $temp1 = "<img src = './1.png' width='100px'>"; $temp2 = "<button>aaa</button>"; $temp3 = "<h1>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>";
结果:
Zend源码分析:
public function filter($value) { $value = (string) $value; // Strip HTML comments first while (strpos($value, '<!--') !== false) { $pos = strrpos($value, '<!--'); $start = substr($value, 0, $pos); $value = substr($value, $pos); // If there is no comment closing tag, strip whole text if (!preg_match('/--\s*>/s', $value)) { $value = ''; } else { $value = preg_replace('/<(?:!(?:--[\s\S]*?--\s*)?(>))/s', '', $value); } $value = $start . $value; } // Initialize accumulator for filtered data $dataFiltered = ''; // Parse the input data iteratively as regular pre-tag text followed by a // tag; either may be empty strings preg_match_all('/([^<]*)(<?[^>]*>?)/', (string) $value, $matches); // Iterate over each set of matches foreach ($matches[1] as $index => $preTag) { // If the pre-tag text is non-empty, strip any ">" characters from it if (strlen($preTag)) { $preTag = str_replace('>', '', $preTag); } // If a tag exists in this match, then filter the tag $tag = $matches[2][$index]; if (strlen($tag)) { $tagFiltered = $this->_filterTag($tag); } else { $tagFiltered = ''; } // Add the filtered pre-tag text and filtered tag to the data buffer $dataFiltered .= $preTag . $tagFiltered; } // Return the filtered data return $dataFiltered; }
我表示看不打懂。。。哈哈哈~