search
Homephp教程php手册PHP正则表达式过滤html标签属性(DEMO),正则表达式demo

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

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

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

例如

过滤除了src之外的所有属性:

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

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

过滤设置过滤除了alt和src之外的所有属性

代码如下:

复制代码 代码如下:
$str = preg_replace('/\s(?!(src|alt))[a-zA-Z]+=[^\s]*/iu',' ', $str);

过滤所有html标签的属性的正则表达式:

复制代码 代码如下:
$str = preg_replace("/]*>/i","",$str );

只过滤alt属性的正则表达式:

复制代码 代码如下:
(\s)alt=[^\s]*

过滤所有html标签的属性的正则表达式:

复制代码 代码如下:
$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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment