Home  >  Article  >  Backend Development  >  How to convert php html to text

How to convert php html to text

藏色散人
藏色散人Original
2021-05-20 10:51:071676browse

php How to convert html to text: First create a PHP sample file; then replace the tags in html through the "function html2text($str){...}" method.

How to convert php html to text

The operating environment of this article: Windows 7 system, PHP version 7.1, DELL G3 computer

php function to convert HTML to txt text

Use PHP's preg_replace function to replace tags in HTML.

Code such as:

 function html2text($str){  
  $str = preg_replace("/<style .*?<\/style>/is", "", $str);  $str = preg_replace("/<script .*?<\/script>/is", "", $str);  
 $str = preg_replace("/<br \s*\/?\/>/i", "\n", $str);  
 $str = preg_replace("/<\/?p>/i", "\n\n", $str);  
 $str = preg_replace("/<\/?td>/i", "\n", $str);  
 $str = preg_replace("/<\/?div>/i", "\n", $str);  
 $str = preg_replace("/<\/?blockquote>/i", "\n", $str);  
 $str = preg_replace("/<\/?li>/i", "\n", $str);  
 $str = preg_replace("/\&nbsp\;/i", " ", $str);  
 $str = preg_replace("/\&nbsp/i", " ", $str);  
 $str = preg_replace("/\&amp\;/i", "&", $str);  
 $str = preg_replace("/\&amp/i", "&", $str);    
 $str = preg_replace("/\&lt\;/i", "<", $str);  
 $str = preg_replace("/\&lt/i", "<", $str);  
 $str = preg_replace("/\&ldquo\;/i", &#39;"&#39;, $str);  
 $str = preg_replace("/\&ldquo/i", &#39;"&#39;, $str);  
 $str = preg_replace("/\&lsquo\;/i", "&#39;", $str);  
 $str = preg_replace("/\&lsquo/i", "&#39;", $str);  
 $str = preg_replace("/\&rsquo\;/i", "&#39;", $str);  
 $str = preg_replace("/\&rsquo/i", "&#39;", $str);  
 $str = preg_replace("/\&gt\;/i", ">", $str);   
 $str = preg_replace("/\&gt/i", ">", $str);   
 $str = preg_replace("/\&rdquo\;/i", &#39;"&#39;, $str);   
 $str = preg_replace("/\&rdquo/i", &#39;"&#39;, $str);   
 $str = strip_tags($str);  
 $str = html_entity_decode($str, ENT_QUOTES, $encode);  
 $str = preg_replace("/\&\#.*?\;/i", "", $str);          
 
 return $str;
 }

Recommended learning: "PHP Video Tutorial"

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

Statement:
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