How to remove html tags using php regular expressions

藏色散人
Release: 2023-03-10 22:14:01
Original
3177 people have browsed it

php正则表达式去掉html标签的方法:首先创建一个PHP示例文件;然后通过正则表达式“preg_replace('/\s(?!src)[a-zA-Z]+=[\'\"]{1}[^\'\"]+[\'\"]{1}/iu',);”实现去除。

How to remove html tags using php regular expressions

本文操作环境:windows7系统、PHP7.1版,DELL G3电脑

php正则表达式怎么去掉html标签?

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

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

例如

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

 代码如下:

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

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

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

代码如下:

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

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

代码如下:

$str = preg_replace("/<([a-z]+)[^>]*>/i","",$str );
Copy after login

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

代码如下:

(\s)alt=[^\s]*
Copy after login

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

代码如下:

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

推荐学习:《PHP视频教程

The above is the detailed content of How to remove html tags using php regular expressions. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!