php
  • regex
  • 2010-07-17 116 views 0 likes 
    0

    請參閱代碼:正則表達式解析HTML

    $result = "<b>Associated Names</b>&nbsp;&nbsp;[<a href='http://www.examples.com/authors.html?act=change&id=6141&item=associated'><u>Edit</u></a>]</td> 
         </tr> 
         <tr> 
          <td class='text' align='left'>G&#12539;R<br />G-R<br />   </td>" 
    
    preg_match_all("/<b>Associated Names.{10,100}<td class='text' align='left'>((.*<br \/>)*).*<\/td>/sU", $result, $assoc); 
    var_dump($assoc); 
    ----------------------------------------------------------- 
    RESULT 
    array 
        0 => 
        array 
         0 => string '<b>Associated Names</b></td> 
         </tr> 
         <tr> 
          <td class='text' align='left'>G&#12539;R<br />G-R<br />   </td>' (length=135) 
        1 => 
        array 
         0 => string '' (length=0) 
        2 => 
        array 
         0 => string '' (length=0) 
    

    我希望它返回

    array(
        1 => 
        array 
         0 => string 'G&#12539;R', 
        2 => 
        array 
         0 => string> 'G-R' 
    ) 
    

    是括號的事(()我想解決這個問題,請大家幫忙我

    +0

    什麼是你對符合正則表達式? – quantumSoup 2010-07-17 17:23:40

    +0

    最好不要使用正則表達式來解析HTML。改爲嘗試一個HTML解析器。 – 2010-07-17 17:25:54

    +2

    我們可以在「Ask Question」頁面告訴用戶不要嘗試用正則表達式解析HTML嗎? – 2010-07-17 17:44:17

    回答

    3

    請不要試圖用正則表達式解析HTML,它invokes the wrath of Zalgo

    嘗試使用the DOMxpath來定位您嘗試提取的特定元素和屬性。

    (我會提供一個XPath例子,但它仍然是我學習的列表... :))

    +0

    感謝您的建議 – meotimdihia 2010-07-17 17:28:20

    +0

    不幸的是,有些時候這是唯一的方法,因爲不是每個頁面都格式良好。很多次,Zend Dom Query未能正確創建dom,並且我得到了錯誤的結果。當然不是框架的錯誤,但解析可能會變得混亂。我使用兩種方法,特設。 – johnjohn 2010-07-17 17:31:18

    +0

    @john,您是否試圖首先通過[tidy](http://us2.php.net/manual/en/book.tidy.php)運行該頁面? – Charles 2010-07-17 17:42:31

    相關問題