2013-02-26 100 views
0

解析網頁時,我的解析器停止由於無效的DOM結構。我想通過替換某個節點來修復它。preg_replace如果條件匹配

我發現有一個額外的</div>導致解析器停止。

我需要編寫一個正則表達式,其將檢查: 如果隨後是</div> [即任何</div>沒有起始<div>之間的標記。它將檢查<div,因爲該標籤可能有id或class to follow],那麼最後的</div>將被替換爲<div></div>

即,如果</div>後面跟着</div>,則最後一個將被替換爲<div></div>

在此先感謝。

例如: <div> <img src="/lexus-share/images/spacer.gif" width="2" height="15" border="0" alt=""> </div> <a href="http://www.somedomain.com"><img src="/pub-share/images.jpg"></a> </div>

+0

你可以A:提供一些代碼與你的嘗試和B:澄清你到底想要什麼? – christopher 2013-02-26 13:30:09

+0

也許你可以編輯它到你的問題:) – christopher 2013-02-26 13:35:46

+0

所以你想要檢查每個'

' has a '
'? – christopher 2013-02-26 13:37:37

回答

0

這隻能如果沒有嵌套<div>秒(不知道他們是合法的):

$result = preg_replace(
    '%</div>  # Match a closing div tag 
    (    # Match and capture in group 1... 
    (?:   # ...the following regex: 
     (?!</?div>) # Match (unless a div tag intervenes) 
     .   # any character. 
    )*   # Repeat any number of times. 
    )    # End of capturing group 
    (?=</div>)  # Assert that a closing div tag follows%six', 
    '</div><div>\1', $subject); 

這改變

<div> <img src="/lexus-share/images/spacer.gif" width="2" height="15" border="0" alt=""> </div> <a href="http://www.somedomain.com"><img src="/pub-share/images.jpg"></a> </div> 

<div> <img src="/lexus-share/images/spacer.gif" width="2" height="15" border="0" alt=""> </div><div> <a href="http://www.somedomain.com"><img src="/pub-share/images.jpg"></a> </div> 
0

我會建議你嘗試一種不同的方法,而不是使用正則表達式,因爲它不容易使它與嵌套標記一起工作。

我不知道你正在使用解析文檔的語言,但你可以寫代碼的邏輯是:

通過解析整個文檔搜索的字符串div>,使2個變量來算openingDivs和closingDivs。

如果div>之前的字符是<, openingDivs ++。

如果div>前性格/,closingDivs ++和檢查if (closingDivs > openingDivs)

如果條件永遠爲真,則可以使程序輸出的div的位置或用空格或空替換</div>

希望這會有所幫助。 :)