当前位置:首页 > PHP教程 > php应用 > 列表

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

发布:smiling 来源: PHP粉丝网  添加日期:2021-08-06 10:07:50 浏览: 评论:0 

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

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

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

  1. function html2text($str){ 
  2.  $str = preg_replace("/<style .*?<\\/style>/is", "", $str); 
  3.  $str = preg_replace("/<script .*?<\\/script>/is", "", $str); 
  4.  $str = preg_replace("/<br \\s*\\/>/i", ">>>>", $str); 
  5.  $str = preg_replace("/<\\/?p>/i", ">>>>", $str); 
  6.  $str = preg_replace("/<\\/?td>/i", "", $str); 
  7.  $str = preg_replace("/<\\/?div>/i", ">>>>", $str); 
  8.  $str = preg_replace("/<\\/?blockquote>/i", "", $str); 
  9.  $str = preg_replace("/<\\/?li>/i", ">>>>", $str); 
  10.  $str = preg_replace("/ /i", " ", $str); 
  11.  $str = preg_replace("/ /i", " ", $str); 
  12.  $str = preg_replace("/&/i", "&", $str); 
  13.  $str = preg_replace("/&/i", "&", $str); 
  14.  $str = preg_replace("/</i", "<", $str); 
  15.  $str = preg_replace("/</i", "<", $str); 
  16.  $str = preg_replace("/“/i", '"', $str); 
  17.  $str = preg_replace("/&ldquo/i", '"', $str); 
  18.  $str = preg_replace("/‘/i", "'", $str); 
  19.  $str = preg_replace("/&lsquo/i", "'", $str); 
  20.  $str = preg_replace("/'/i", "'", $str); 
  21.  $str = preg_replace("/&rsquo/i", "'", $str); 
  22.  $str = preg_replace("/>/i", ">", $str); 
  23.  $str = preg_replace("/>/i", ">", $str); 
  24.  $str = preg_replace("/”/i", '"', $str); 
  25.  $str = preg_replace("/&rdquo/i", '"', $str); 
  26.  $str = strip_tags($str); 
  27.  $str = html_entity_decode($str, ENT_QUOTES, "utf-8"); 
  28.  $str = preg_replace("/&#.*?;/i", "", $str); 
  29.  return $str; 
  30. }

Tags: php转换html

分享到: