2010-12-10 43 views
4

我正在尋找一種方法來剝離所有錨標籤,我也希望從','到<br>被刪除,但<br>應該保持。PHP:正則表達式和特定標籤剝離

髒輸入:

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> 

'); 
+0

第一行讀爲: 我正在尋找一種方法來去除所有錨標記,我也希望從','到linebreak標記的所有內容都被刪除,但換行符應該保持爲thr。 – ehmad11 2010-12-10 14:01:02

+0

沒有任何其他方式沒有使用HTML淨化器? ! – ehmad11 2010-12-10 14:11:08

+0

試試我的答案,看看它是否適合你。 – BoltClock 2010-12-10 14:15:30

回答

1

通常是不好用正則表達式來處理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想要什麼。

+0

它忽略每局結束爲止這是不希望.. 代碼給出了這樣的輸出: 抽象的HLTH 客戶代表 忽略「會計」,因爲它的之間「」最後BR – ehmad11 2010-12-10 14:32:43

+0

@ ehmad1:你的意思是所有三條線都在一個單一的字符串? – BoltClock 2010-12-10 14:33:53

+0

是的所有行都在一個字符串中 – ehmad11 2010-12-10 14:37:09

0

strip-tags()的標籤,str_replace()strpos()爲其他的事情。

+0

strip_tags **僅限**允許某些標籤保留,但OP要反向行爲 – ajreal 2010-12-10 14:05:44

+0

哦,是的,沒錯。無論如何請留下答案,也許有人對此感興趣。 – KingCrunch 2010-12-10 14:08:05

0

HTML Purifier是你的朋友。它有靈活的選擇,並且非常複雜。用str_replace或正則表達式做這樣的事情是錯誤

+0

我沒有downvote,但爲什麼有一個HTML清潔劑回答upvote和downvote這一個? – BoltClock 2010-12-10 14:14:53

+0

Upvoting反擊downvote。 – BoltClock 2010-12-10 14:27:49

0
$clean_string = strip_tags($original_string, '<br>'); 

這將除去br標籤以外的所有東西。

正如KingCrunch所說,其餘爲str_replacestrpos

0

strip_tags有第二個參數,它允許你提供一個允許標籤的字符串。這將去除所有標籤,除非你提供的:

$string = strip_tags($string, '<br>'); // will leave <br>-tags in place