2012-07-12 61 views
0

我有一個HTML代碼:正則表達式來查找所有A標籤裏面不包含標籤IMG?

<a href="/in-bai-viet--Choang-n20120711033726647.chn" target="_blank">In<img src="/Images/printer.png" alt="In bài viết này" /> 
</a> 
<a target="_blank" rel="nofollow" href="http://ttvn.vn/">Thiên Lam - TTVN 
</a> 
<a href="/tinh-yeu-hon-nhan/20120709102954599/Chay-lang-.chn" title="'abc'"> 
abcd 
</a> 

我需要刪除所有不包含在它裏面的img標籤的標籤。 我使用正則表達式:

preg_replace('/<a(.*)[^img](.*)<\/a>/si', '', $string); 

我也試過在^(?!.+<img.+)<a href=\"?\'?.+\"?\'?>.+</a>$Regular expression, how to find all tags A which do not contain tag IMG inside it?失敗。

謝謝

+7

你不應該使用正則表達式來解析HTML。 http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags – 2012-07-12 04:06:20

+0

你正在使用哪種語言? JavaScript的? PHP? C#?正如下面的nhahtdh所提到的,在每種語言中實現正則表達式都有一些問題。此外,可能有更好的方法來實現您所用語言所需的內容。 – rikitikitik 2012-07-12 04:51:52

+0

@rikitikitik:顯然是PHP。將添加一個標籤。 – 2012-07-12 05:23:21

回答

0

使用這一個:

(<a[^<]*>.*<img[^>]*>[^<]*</a>) 

,並用空字符串替換。 It tested here

+0

我更新了我的答案。 – Ria 2012-07-12 04:16:55

+0

謝謝,但它不起作用。 – kaka167 2012-07-12 04:48:57

+0

我將[測試樣本](http://regexr.com?31gol)添加到我的答案中。 – Ria 2012-07-12 04:52:45

0

我注意到這個老問題沒有答案,所以我想我會提供一個可靠的解決方案。 Ria的回答並不是在關閉a標記中跳過/,因此它會在鏈接的演示中導致錯誤。此外,當提供的樣本翻倍(與自身連接)時,Ria的正則表達式模式失敗,因爲它太貪婪,並且抓取多個標記,更不用說它比我的模式慢4倍以上。

模式闡釋(demo):

(    #Start capture group 
    <a[^<]*> #Greedily match the opening a tag, no other tags 
    [^<]*  #Greedily match characters of any length before <img 
    <img[^>]*> #Greedily match the whole img tag 
    [^<]*  #Greedily match characters of any length after <img 
    <\/a>  #Match the closing a tag 
)    #End capture group 

代碼(demo):

<?php 
$string="<a href=\"/in-bai-viet--Choang-n20120711033726647.chn\" target=\"_blank\">In<img src=\"/Images/printer.png\" alt=\"In bài viết này\" /> 
</a> 
<a target=\"_blank\" rel=\"nofollow\" href=\"http://ttvn.vn/\">Thiên Lam - TTVN 
</a> 
<a href=\"/tinh-yeu-hon-nhan/20120709102954599/Chay-lang-.chn\" title=\"'abc'\"> 
abcd 
</a> 
<a href=\"/in-bai-viet--Choang-n20120711033726647.chn\" target=\"_blank\">In<img src=\"/Images/printer.png\" alt=\"In bài viết này\" /> 
</a> 
<a target=\"_blank\" rel=\"nofollow\" href=\"http://ttvn.vn/\">Thiên Lam - TTVN 
</a> 
<a href=\"/tinh-yeu-hon-nhan/20120709102954599/Chay-lang-.chn\" title=\"'abc'\"> 
abcd 
</a>"; 
echo preg_replace('/(<a[^>]*>[^<]*<img[^>]*>[^<]*<\/a>)\r?\n?/si',NULL,$string); 
?> 

輸出:

<a target="_blank" rel="nofollow" href="http://ttvn.vn/">Thiên Lam - TTVN 
</a> 
<a href="/tinh-yeu-hon-nhan/20120709102954599/Chay-lang-.chn" title="'abc'"> 
abcd 
</a> 
<a target="_blank" rel="nofollow" href="http://ttvn.vn/">Thiên Lam - TTVN 
</a> 
<a href="/tinh-yeu-hon-nhan/20120709102954599/Chay-lang-.chn" title="'abc'"> 
abcd 
</a> 

雖然這個問題很可能已經被在現實生活中解決, /或者不再重要,我只想把這個鬆散的結局捆綁在一起。

相關問題