php處理html字串__html

來源:互聯網
上載者:User
在開發APP介面的時候,我們經常需要將html富文本字串進行處理,PHP中內建了許多有用的函數來給我們進行使用 需要用到的函數: str_replace() 字串替換 html_entity_decode() html字串轉html標籤 strip_tags() 除去所有html標籤 preg_match_all() 全域正則匹配字串 array_unique() 去除數組中重複的元素(用於解決全域正則匹配帶來的元素重複的問題) array_flip() 將索引值交換,因為鍵名不能重複,所以重複元素會被去掉,兩次flip下來就能夠得到不重複的索引值數組 array_values() 返回只有索引值無鍵名的數組 快速去除html字元
$bewrite = strip_tags(html_entity_decode($htmlStr),'<br>');

先轉HTML標籤再去除標籤,但是注意保留換列標籤,在APP中的文字依然需要簡單地排版。
接著我們再把br標籤再轉成本地APP的\n

$bewrite = str_replace('<br/>','\n',$bewrite);

但似乎字串還是沒有除乾淨,因為會殘餘一些html本身的換行字元&和空格,再替換一次

$bewrite = str_replace('&nbsp;',' ',$bewrite);$bewrite = str_replace('&amp;','',$bewrite);

但通常情況下,我們的HTML字串中不僅有文本,還有圖片,img中的src屬性也必須要挑出來 正則匹配標籤屬性

下面我以img中匹配src圖片地址為例子

$unmatchedstr = html_entity_decode($data['secondgoods_bewrite']); //轉html字串preg_match_all('/\<img.*?src\=\"(.*?)\"[^>]*>/i',$unmatchedstr,$match);//正則匹配圖片src地址

但這還沒完,我們發現正則出來的連結有許多的重複的連結,我們必須要去除變數$match[1]中重複的值

$matches = array_unique($match[1]);//來兩次array_flip()或許比unique更加高效一些$matchresult = array_values($matches);//取索引值數組的值,去掉鍵名就完成了

附文:

對於遠端src地址,有一種特殊的正則匹配可以排除掉本地的圖片

preg_match_all('/((http|https):\/\/)+(\w+\.)+(\w+)[\w\/\.\-]*(jpg|gif|png)/',$unmatchedstr,$matches); 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.