php html格式轉文本格式代碼
來源:程序員人生 發布時間:2014-01-10 03:59:48 閱讀次數:2425次
在php中將html標簽轉換成純文本的方法有不少,像php自帶了函數strip_tags它就可以把html直接轉換在純文本文格式了,下面我來具體來看看各種轉換代碼。
先來看strip_tags()函數用法,下面的例子刪除<a>標記之外的所有標記,代碼如下:
- <?php $input = "This <a href="http:
- is <strong>yanshare</strong>!";
- echo strip_tags($input, "<a>");
- ?>
輸入結果:This <a href="http://www.phpfensi.com/">example</a>,這里就連接連接與連接中的內容都過濾掉了,我們如果想保留A中的內容可以參考下面代碼
strip_tags有一個可選的參數allowable_tags指定在此過程中可以跳過的標記,下面的例子使用了strip_tags()刪除字符串中的所以HTML標記,代碼如下:
- <?php $input = "Email<a href="example@example.com">example@example.com</a>";
- echo strip_tags($input);
- ?>
這回返回以下結果:Email example@example.com
一個自定義的將html轉換為無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", "nn", $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("/“/i", '"', $str);
- $str = preg_replace("/&ldquo/i", '"', $str);
- $str = preg_replace("/‘/i", "'", $str);
- $str = preg_replace("/&lsquo/i", "'", $str);
- $str = preg_replace("/’/i", "'", $str);
- $str = preg_replace("/&rsquo/i", "'", $str);
- $str = preg_replace("/>/i", ">", $str);
- $str = preg_replace("/>/i", ">", $str);
- $str = preg_replace("/”/i", '"', $str);
- $str = preg_replace("/&rdquo/i", '"', $str);
- $str = strip_tags($str);
- $str = html_entity_decode($str, ENT_QUOTES, "utf-8");
- $str = preg_replace("/&#.*?;/i", "", $str);
- return $str;
- }
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈