php实现转换html格式为文本格式的方法

yipeiwu_com5年前PHP代码库

本文实例讲述了php实现转换html格式为文本格式的方法。分享给大家供大家参考,具体如下:

有时候需要转换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("/<\\/?div>/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", '"', $str);
 $str = preg_replace("/&ldquo/i", '"', $str);
 $str = preg_replace("/‘/i", "'", $str);
 $str = preg_replace("/&lsquo/i", "'", $str);
 $str = preg_replace("/'/i", "'", $str);
 $str = preg_replace("/&rsquo/i", "'", $str);
 $str = preg_replace("/>/i", ">", $str);
 $str = preg_replace("/>/i", ">", $str);
 $str = preg_replace("/”/i", '"', $str);
 $str = preg_replace("/&rdquo/i", '"', $str);
 $str = strip_tags($str);
 $str = html_entity_decode($str, ENT_QUOTES, "utf-8");
 $str = preg_replace("/&#.*?;/i", "", $str);
 return $str;
}

PS:小编在这里推荐一款本站的php格式化美化的排版工具帮助大家在以后的PHP程序设计中进行代码排版:
 
php代码在线格式化美化工具:http://tools.jb51.net/code/phpformat

对于代码及编码转换感兴趣的朋友还可参考本站在线工具:

在线编码转换工具(utf-8/utf-32/Punycode/Base64):

http://tools.jb51.net/transcoding/decode_encode_tool

在线UBB/HTML代码转换工具:

http://tools.jb51.net/transcoding/ubb2html

中文繁体字简体字转换(繁简转换)工具:

http://tools.jb51.net/transcoding/convertzh

在线图片转换BASE64工具:

http://tools.jb51.net/transcoding/img2base64

更多关于PHP相关内容感兴趣的读者可查看本站专题:《PHP数组(Array)操作技巧大全》、《php排序算法总结》、《PHP常用遍历算法与技巧总结》、《PHP数据结构与算法教程》、《php程序设计算法总结》、《PHP数学运算技巧总结》、《php正则表达式用法总结》、《PHP运算与运算符用法总结》、《php字符串(string)用法总结》及《php常见数据库操作技巧汇总

希望本文所述对大家PHP程序设计有所帮助。

相关文章

php实现scws中文分词搜索的方法

本文实例讲述了php实现scws中文分词搜索的方法。分享给大家供大家参考,具体如下: 1、4个文件(本站下载地址。)解压后,放到一个地方 eg:E:/wamp/scws 2、php.in...

Discuz Uchome ajaxpost小技巧

比如默认submit按钮这样操作:onclick="ajaxpost('formid')";之类的,我们可以先这样。。 onclick="$('__formid').innerText=...

一些php项目中比较通用的php自建函数的详解

以下一些php函数是我们it动力最常用的项目开发函数,这些函数还算是在比较多的项目中使用到的,也是比较通用的。1.请求接口的处理函数复制代码 代码如下:/**  * curl访...

相对路径转化成绝对路径

提取 Gregarius中的一个函数。可以把网页中的相对路径自动转化成绝对路径。 <?  function relative_to_absolute(...

PHP设置Cookie的HTTPONLY属性方法

httponly是微软对cookie做的扩展,这个主要是解决用户的cookie可能被盗用的问题。 大家都知道,当我们去邮箱或者论坛登陆后,服务器会写一些cookie到我们的浏览器,当下次...