Home >Backend Development >PHP Tutorial >PHP正则表达式过滤html标签属性(DEMO)_PHP

PHP正则表达式过滤html标签属性(DEMO)_PHP

WBOY
WBOYOriginal
2016-05-29 11:47:051042browse

过滤html标签在php中可以有内置的函数了,但它过滤的太干净了,我们就整理了一下些利用正则来过滤指定html标签的例子,具体如下所示。

采集的时候有时候需要过滤掉多余的标签属性,比如 img标签过滤掉除了src属性之外的所有属性例如删除titile alt等属性以及一些脚的onclick属性等。

例如

代码如下:


$str= preg_replace('/\s(?!src)[a-zA-Z]+=[\'\"]{1}[^\'\"]+[\'\"]{1}/iu',' $str);

上面的实例代码是过滤掉除了src属性外的所有标签属性.

代码如下:


$str = preg_replace('/\s(?!(src|alt))[a-zA-Z]+=[^\s]*/iu',' ', $str);

代码如下:


$str = preg_replace("/]*>/i","",$str );

代码如下:


(\s)alt=[^\s]*

代码如下:


$search = array ("'<script>]*&#63;>.*&#63;</script>'si", // 去掉 javascript
"']*?>'si", // 去掉 HTML 标记
"'([\r\n])[\s]+'", // 去掉空白字符
"'&(quot|#34);'i", // 替换 HTML 实体
"'&(amp|#38);'i",
"'&(lt|#60);'i",
"'&(gt|#62);'i",
"'&(nbsp|#160);'i"
); // 作为 PHP 代码运行
$replace = array ("","","\\1","\"","&",""," ");
$html = preg_replace($search, $replace, $html);

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn