2013-07-12 28 views
-1

什麼我只是試圖做的就是把下面的代碼:使用正則表達式的preg_match找開錨標記,搶類屬性

$Anchors = '<a href="#" class="test1"><div class="test2"><a href="#" class="test3"><div class="test4">' 

,最後一錨標記的類屬性的值,在這個例子是「test3」。到目前爲止,我有這個:

if(preg_match('/(<a\s.*)(class="|\')([^-\'"]*)("|\')?.*?([^>])/i',$Anchors,$matches)){ 

但顯然它沒有做我想做的事情,任何幫助?

+4

強制性「不使用正則表達式來解析HTML 「評論。 – nickb

+0

你不能用正則表達式解析[X] HTML。因爲HTML不能被正則表達式解析。正則表達式不是一個可以用來正確解析HTML的工具。 ...O̚N̐Y̡H̸̡̪̯ͨ͊̽̅̾Ȩ̸̡̬̩̪̯̾͛ͪ̈ͨ͊̽̅̾͘Ȩ̬̩̾͛ͪ̈͘C̷̙̝͖ͭ̏ͥͮ͟Oͮ͏̮̪̝͍M̖͊̒ͪͩͬ̚̚͜... http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags?page=1&tab=active#tab-top – user20232359723568423357842364

回答

2

說明

這個正則表達式:

  • 比賽從最後一個錨標記你字符串
  • 捕捉值類屬性
  • 避免許多與使用正則表達式的潛在問題,以搜索HTML字符串

 

.*<a\b(?=\s) # capture the open tag 
(?=(?:[^>=]|='[^']*'|="[^"]*"|=[^'"][^\s>]*)*?\sclass=['"]([^"]*)['"]?) # capture the src attribute value 
(?:[^>=]|='[^']*'|="[^"]*"|=[^'"\s]*)*"\s?\/?> # get the entire tag 

enter image description here

當實例

現場示例:http://www.rubular.com/r/G5F6AD5UyL

示例文本

注意最後一個標籤具有難以邊緣情況

<a href="#" class="test1"><div class="test2"> 
<a onmouseover=' class="NotTheClass" ; funClassRotator(class) ; ' class="test3" href="#" ><div class="test4"> 

捕捉組

[0][0] = <a href="#" class="test1"><div class="test2"><a href="#" onmouseover=' class="NotTheClass" ; funClassRotator(class) ; ' class="test3"> 
[0][1] = test3 
+1

謝謝!做得很好。 – SReca

1

它會更快使用simplehtmldom

使用 ganonsimplehtmldom

例如

foreach($html->find('a') as $element) 
    echo $element->class . '<br>';