How to convert php html to text

藏色散人
Release: 2023-03-09 19:54:02
Original
1768 people have browsed it

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;
 }
Copy after login

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!

Related labels:
php
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