php html格式轉文字格式設定代碼

來源:互聯網
上載者:User

先來看strip_tags()函數用法

下面的例子刪除<a>標記之外的所有標記:

 代碼如下 複製代碼

<!--?php <br ?--> $input = "This <a href="http://www.111cn.net/">example</a>
is <strong>yanshare</strong>!";
echo strip_tags($input, "<a>");
?&gt;
</a>

輸入結果

This <a href="http://www.111cn.net/">example</a>
is yanshare!

這裡就串連串連與串連中的內容都過濾掉了,我們如果想保留A中的內容可以參考下面代碼

strip_tags有一個可選的參數allowable_tags指定在此過程中可以跳過的標記。下面的例子使用了strip_tags()刪除字串中的所以HTML標記:

 代碼如下 複製代碼


<!--?php <br ?--> $input = "Email <a href="example@example.com">example@example.com</a>";
echo strip_tags($input);
?&gt;
這回返回以下結果:

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("/&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", '"', $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("/&gt;/i", ">", $str);
   $str = preg_replace("/&gt/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, "utf-8");
   $str = preg_replace("/&#.*?;/i", "", $str);

   return $str;
  }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.