Home > Backend Development > PHP Tutorial > PHP清除html标签(清除空格,换行符,制表符,注释标记)

PHP清除html标签(清除空格,换行符,制表符,注释标记)

WBOY
Release: 2016-06-20 13:01:54
Original
1396 people have browsed it

分享一种利用 php 清除html代码中的空格,换行符,制表符,注释标记等以达到压缩输出 html 的目的。

<p>/**</p>*压缩html:清除换行符,清除制表符,去掉注释标记<br />*@param $string<br />*@return 压缩后的$string<br />**/<br />function compress_html($string){<br />	$string=str_replace("\r\n",'',$string);//清除换行符<br />	$string=str_replace("\n",'',$string);//清除换行符<br />	$string=str_replace("\t",'',$string);//清除制表符<br />	$pattern=array(<br />		"/> *([^ ]*) *</",//去掉注释标记 <br />		"/[\s]+/",<br />		"/<!--[^!]*-->/",<br />		"/\" /",<br />		"/ \"/",<br />		"'/\*[^*]*\*/'"<br />	);<br />	$replace=array(<br />		">\\1<",<br />		" ",<br />		"",<br />		"\"",<br />		"\"",<br />		""<br />	);<br />	return preg_replace($pattern,$replace,$string);<br /><p>}
Copy after login

下面方法来实现这个想法。

思路如下:

<p>function cleanHtml($str){ </p>	$str=trim($str);<br />	$str=strip_tags($str,"");<br />	$str=ereg_replace("\t","",$str);<br />	$str=ereg_replace("\r\n","",$str);<br />	$str=ereg_replace("\r","",$str);<br />	$str=ereg_replace("\n","",$str);<br />	$str=ereg_replace(" "," ",$str);<br />	return trim($str);<br />}
Copy after login


Related labels:
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