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.
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("/\ \;/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("/\&ldquo/i", '"', $str); $str = preg_replace("/\&lsquo\;/i", "'", $str); $str = preg_replace("/\&lsquo/i", "'", $str); $str = preg_replace("/\&rsquo\;/i", "'", $str); $str = preg_replace("/\&rsquo/i", "'", $str); $str = preg_replace("/\>\;/i", ">", $str); $str = preg_replace("/\>/i", ">", $str); $str = preg_replace("/\&rdquo\;/i", '"', $str); $str = preg_replace("/\&rdquo/i", '"', $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!