[英]PHP: regexp and specific tags stripping
我正在尋找一種剝離所有錨標簽的方法,我也希望刪除從','到<br>
所有內容,但<br>
應該保留thr。
臟輸入:
Abstractor HLTH<br>
Account Representative, Major <a href="#P">P</a><br>
Accountant <a href="#NP">NP</a>, <a href="#M">M</a>, <a href="#REA">REA</a>, <a href="#SKI">SKI</a><br>
它應該像這樣:
Abstractor HLTH<br>
Account Representative<br>
Accountant <br>
請幫忙!
-以下是臟文字:
$str = sprintf('
Abstractor HLTH<br>
Account Representative, Major <a href="#P">P</a><br>
Accountant <a href="#NP">NP</a>, <a href="#M">M</a>, <a href="#REA">REA</a>, <a href="#SKI">SKI</a><br>
Accountant, Cost I & II (See Cost Accountant I, II) <a href="#FR">FR</a><br>
Accountant, General <a href="#G">G</a><br>
Accountant, General I (Junior) (See General Accountant) <a href="#FR">FR</a>, <a href="#O/G">O/G</a>, <a href="#W">W</a><br>
Accountant, General II (Intermediate) (See General Accountant) <a href="#FR">FR</a>, <a href="#O/G">O/G</a>, <a href="#W">W</a>, <a href="#HA">HA</a> <br>
Accountant, General III (Senior) (See General Accountant) <a href="#FR">FR</a>, <a href="#O/G">O/G</a>, <a href="#W">W</a> <br>
');
我強烈建議您使用HTML Purifier http://htmlpurifier.org/
它的設置非常簡單,聲譽卓著,功能強大。
通常,使用正則表達式來處理HTML字符串是很不好的,但是假設所有鏈接都是這樣構成的,那么使用preg_replace()
不會造成問題。 嘗試這個
// Removes all links
$str = preg_replace("/<a href=\"#([A-Z\\/]+?)\">\\1<\\/a>(?:, )?/i", "", $str);
// Strip the comma and everything from the comma
// to the next <br> in the line
$str = preg_replace("/,(.*?)(?=<br>)/i", "", $str);
對於建議strip_tags()
的其他答案:它不會刪除它剝離的一對HTML標記所包含的文本。 例如
Accountant <a href="#NP">NP</a>
變成
Accountant NP
這不是OP想要的。
HTML Purifier是您的朋友。 它具有靈活的選項,並且非常復雜。 用str_replace或正則表達式執行此類操作是錯誤的 。
$clean_string = strip_tags($original_string, '<br>');
這將除去br標簽以外的所有內容。
正如KingCrunch所說,其余部分使用str_replace
和strpos
。
strip_tags有第二個參數,它允許您提供一串允許的標簽。 它將剝離除您提供的標簽以外的所有標簽:
$string = strip_tags($string, '<br>'); // will leave <br>-tags in place
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.