2014-01-27 15 views
0

比方說,我有一個HTML類似這樣的標記:正則表達式:如何匹配給定html tah外部的單詞?

<p> 
    <h1>Some header, which I don't want to match</h1> 
    Some text - match it. 
    <a href="some-file.html">Some link. Don't match neither href nor link text.<a> 
    <span>Some word, which needs to be matched</span> 
</p> 

在幾句話,我想在整個的內容相匹配的一些詞,除了給定的HTML標籤(及其屬性)。在給定的例子中,我想排除h1和一個標籤。

預期結果「某些」通過「測試」後替換:

<p> 
    <h1>Some header, which I don't want to match</h1> 
    Test text - match it. 
    <a href="some-file.html">Some link. Don't match neither href nor link text.<a> 
    <span>Test word, which needs to be matched</span> 
</p> 
+4

使用PHP DOM和XPath – zerkms

+0

好的,謝謝,這是一些解決方案,但我仍然會很高興知道解決的正則表達式的方法它:) – Piotrycjan

+0

nope,完全不同的主題:) – Piotrycjan

回答

0

您可以使用:<(a|h1)[^\>]*?>(some)[^\<]*?<\/\1>匹配包含some線和HTML標記之間。

並檢查一行是否不符合此正則表達式,然後用您所需的替換文本替換一些單詞(如果有的話)。

Demo

說明:

enter image description here

+1

」排除h1和一個標籤「 – zerkms

+0

是的,它會排除幾乎所有的html標籤 –

+0

OP不想排除所有的html標籤,但有些 – zerkms