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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路