Converting HTML to text in PHP provides the built-in function strip_tags, but sometimes this function is not enough. Here is a summary of some user-defined functions for your reference.
The most commonly used php function strip_tags
The code is as follows | Copy code | ||||
$mystr=<< SATO; $str=strip_tags($mystr); //At this point, I have achieved my purpose of converting HTML to TXT text, haha, it is so convenient to use this function //The following are some word segmentation and other operations of the plug-in, so I won’t go into details here ?> |
Custom function
The code is as follows | Copy code | ||||
|
Later I saw a method written in PHP from the Internet. This method can also be used to convert HTML to TXT text. I personally think it is quite practical. I will share it here. The code is as follows:
代码如下 | 复制代码 |
function HtmlToText($str){ $str=preg_replace("/ $alltext="";//用于保存TXT文本的变量 $start=1;//用于检测<左、>右标签的控制开关 for($i=0;$i $start=1; }else if($start==1){//截取功能 if($str[$i]=="<"){//如果字符是<左标签,则使用|替换 $start=0; $alltext.="|"; }else if(ord($str[$i])>31){//如果字符是ASCII大于31的有效字符,则将字符添加到$alltext变量中 $alltext.=$str[$i]; } } } //下方是去除空格和一些特殊字符的操作 $alltext = str_replace(" "," ",$alltext); $alltext = preg_replace("/&([^;&]*)(;|&)/","",$alltext); $alltext = preg_replace("/[ ]+/s"," ",$alltext); return $alltext; } |
使用上面这个方法也可以实现将简答的HTML代码转换为TXT文本。
例3
代码如下 | 复制代码 |
function html2text($str,$encode = 'GB2312') $str = preg_replace("/ |