使用DOMphp解析事件属性


parse event attributes using DOM php

可能重复:
获取A元素的href属性

我想知道如何使用DOMphp解析事件属性?例如

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

我需要获取onload事件属性中的链接。有可能吗?

不使用preg_match并解析整个html。使用DOMDocument,我们可以使用getAttribute('src')或getAttribute('ref')获取所有其他属性,如"src"、"href"等。有没有类似的方法来获取事件属性?在"加载"事件中出现的任何链接都应该被捕获

谢谢。

DOM php API中没有任何方法可以从onload属性中为您提供URL,因此您必须使用下面建议的方法(或类似方法)。但首先要获得属性:

$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')

一旦你得到了,你可以使用一个简单的正则表达式来提取URL:

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

像这样:

$mathes = array();
preg_match('`(?:.+?)(?<url>https?://['w'd.&?=]+)(?:.+?)`', $attribute, $matches);
echo $matches['url']; // outputs https://google.com