douqin3245 2012-09-11 07:05
浏览 51
已采纳

使用DOM php [duplicate]解析事件属性

Possible Duplicate:
Grabbing the href attribute of an A element

I would like to know how can we parse the event attributes using DOM php? For example

<body onload="javascript:PopWin('http://google.com')">

I need to get the link inside the onload event attribute. is it possible?

Not using preg_match and parse the entire html. using DOMDocument, we can get all other attributes like "src", "href" etc using getAttribute('src') or getAttribute('href'). Is there any similar way for getting the event attribute? Any link that comes in the event "onload" should be catched

Thanks.

  • 写回答

1条回答 默认 最新

  • dqr91899 2012-09-11 07:29
    关注

    There is no method in the DOM php API that will give you the URL from the onload property so you have to use a method like I suggest below (or similar). But first get the attribute:

    $body = "<body onload=\"javascript:PopWin('http://google.com')\"></body>";
    
    $doc = new DOMDocument(); 
    $doc->loadHTML($body);
    
    $bodyElements = $doc->getElementsByTagName("body"); 
    $body = $bodyElements->item(0);
    
    $attribute = $body->getAttribute('onload');
    
    echo $attribute; // outputs: javascript:PopWin('https://google.com')
    

    Once you got that you can use a simple regular expression to extract the URL:

    (?:.+?)(https?://[\w\d.&?=]+)(?:.+?)
    

    Like this:

    $mathes = array();
    preg_match('`(?:.+?)(?<url>https?://[\w\d.&?=]+)(?:.+?)`', $attribute, $matches);
    
    echo $matches['url']; // outputs https://google.com
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?