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

报告相同问题?

悬赏问题

  • ¥15 qt+ffmpeg报错non-existing PPS 0 referenced
  • ¥15 FOC simulink
  • ¥15 咨询一下有关于王者荣耀赢藏战绩
  • ¥50 MacOS 使用虚拟机安装k8s
  • ¥500 亚马逊 COOKIE我如何才能实现 登录一个亚马逊账户 下发新 COOKIE ..我使用下发新COOKIE 导入ADS 指纹浏览器登录,我把账户密码 修改过后,原来下发新COOKIE 不会失效的方式
  • ¥20 玩游戏gpu和cpu利用率特别低,玩游戏卡顿
  • ¥25 oracle中的正则匹配
  • ¥15 关于#vscode#的问题:把软件卸载不会再出现蓝屏
  • ¥15 vimplus出现的错误
  • ¥30 怎么使用AVL fire ESE软件自带的优化模式来优化设计Soot和NOx?