Home > Backend Development > PHP Tutorial > How to convert html format to text format in php

How to convert html format to text format in php

墨辰丷
Release: 2023-03-29 13:40:01
Original
3555 people have browsed it

这篇文章主要介绍了php实现转换html格式为文本格式的方法,通过一个自定义函数实现针对HTML标签的过滤,涉及php正则替换的相关操作技巧,需要的朋友可以参考下

有时候需要转换html格式的字符串为文本,但又需要保持一定的格式,比如要求段落变成的分段格式就可以用下面这个函数

function html2text($str){
 $str = preg_replace("/<style .*?<\\/style>/is", "", $str);
 $str = preg_replace("/<script .*?<\\/script>/is", "", $str);
 $str = preg_replace("/<br \\s*\\/>/i", ">>>>", $str);
 $str = preg_replace("/<\\/?p>/i", ">>>>", $str);
 $str = preg_replace("/<\\/?td>/i", "", $str);
 $str = preg_replace("/<\\/?p>/i", ">>>>", $str);
 $str = preg_replace("/<\\/?blockquote>/i", "", $str);
 $str = preg_replace("/<\\/?li>/i", ">>>>", $str);
 $str = preg_replace("/ /i", " ", $str);
 $str = preg_replace("/ /i", " ", $str);
 $str = preg_replace("/&/i", "&", $str);
 $str = preg_replace("/&/i", "&", $str);
 $str = preg_replace("/</i", "<", $str);
 $str = preg_replace("/</i", "<", $str);
 $str = preg_replace("/“/i", &#39;"&#39;, $str);
 $str = preg_replace("/&ldquo/i", &#39;"&#39;, $str);
 $str = preg_replace("/‘/i", "&#39;", $str);
 $str = preg_replace("/&lsquo/i", "&#39;", $str);
 $str = preg_replace("/&#39;/i", "&#39;", $str);
 $str = preg_replace("/&rsquo/i", "&#39;", $str);
 $str = preg_replace("/>/i", ">", $str);
 $str = preg_replace("/>/i", ">", $str);
 $str = preg_replace("/”/i", &#39;"&#39;, $str);
 $str = preg_replace("/&rdquo/i", &#39;"&#39;, $str);
 $str = strip_tags($str);
 $str = html_entity_decode($str, ENT_QUOTES, "utf-8");
 $str = preg_replace("/.*?;/i", "", $str);
 return $str;
}
Copy after login

总结:以上就是本篇文的全部内容,希望能对大家的学习有所帮助。

相关推荐:

php通过各种函数判断0和空

php识别翻转iphone拍摄的颠倒图片

php微信公众平台开发之微信群发信息实例分享

The above is the detailed content of How to convert html format to text format in php. For more information, please follow other related articles on the PHP Chinese website!

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