2016-11-02 71 views
1

我想在我的字符串選擇不自定義類標籤有另一個標籤不能選擇的, 字符串:正則表達式匹配<a>標籤

<h3 class="r"><a dir="rtl" class="sla" href="#"><span>test<span></a></h3> 
<h3>test1</h3> 
<h3 class="r"><a class="test" href="#">test2</a></h3> 
<h3>test3</h3> 

我註冊:

preg_match_all('@<h3\s*class="r">\s*<a[^<>]*href="([^<>]*)"[^<>]*>(.*)</a>\s*</h3>@siU', 
     $file, $matches); 

我怎麼能選擇模式中的所有標籤不帶class =「sla」

+2

旁註:我不能完全肯定這一點,但使用'@'這裏的符號可能不是一個好主意。 PHP可能會將其視爲錯誤抑制器。嘗試一個不同的。 –

+3

使用DOM與'//a [not(@ class =「sla」)]'xpath。 –

+0

[你如何解析和處理PHP中的HTML/XML?](http://stackoverflow.com/questions/3577641/how-do-you-parse-and-process-html-xml-in-php ) – chris85

回答

1

使用正則表達式「negative lookahead」<a(?![^<>]*sla)...將丟棄「a」標籤內所有「sla」的結果。

preg_match_all('@<h3\s*class="r">\s*<a(?![^<>]*sla)[^<>]*href="([^<>]*)"[^<>]*>(.*)<\/a>\s*<\/h3>@siU', 
$file, $matches) 

您也可以使用更確切的說法:<a(?![^<>]*class=\"sla\")...

有關「環視」表達的更多信息:http://www.regular-expressions.info/lookaround.html