首頁  >  文章  >  後端開發  >  php html怎麼轉text

php html怎麼轉text

藏色散人
藏色散人原創
2021-05-20 10:51:071676瀏覽

php html轉text的方法:先建立一個PHP範例檔案;然後透過「function html2text($str){...}」方法將html中的標記替換即可。

php html怎麼轉text

本文操作環境:Windows7系統、PHP7.1版,DELL G3電腦

php將HTML轉換為txt文字的函數

利用php的preg_replace函數對html中的標記進行替換。

程式碼如:

 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;
 }

推薦學習:《PHP影片教學

以上是php html怎麼轉text的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn