使用domphp解析事件属性

使用domphp解析事件属性,php,dom,Php,Dom,可能重复: 我想知道如何使用DOM php解析事件属性? 比如说 <body onload="javascript:PopWin('http://google.com')"> 我需要获取onload事件属性中的链接。 可能吗 不使用preg_匹配并解析整个html。使用DOMDocument,我们可以使用getAttribute('src')或getAttribute('href')获取所有其他属性,如“src”、“href”等。获取事件属性是否有类似的方法?在“onload

可能重复:

我想知道如何使用DOM php解析事件属性? 比如说

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

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

不使用preg_匹配并解析整个html。使用DOMDocument,我们可以使用getAttribute('src')或getAttribute('href')获取所有其他属性,如“src”、“href”等。获取事件属性是否有类似的方法?在“onload”事件中出现的任何链接都应该被捕获


谢谢。

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')
像这样:

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

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

使用DOM php???我不确定我是否理解你。。但是你基本上是想解析一个页面的内容,并检索
PopWin(“
和第一次出现
”)“>
”之间的任何内容吗?不。不使用preg_匹配并解析整个html。使用DOMDocument,我们可以使用getAttribute('src')或getAttribute('href')获得所有其他属性,如“src”、“href”等。获取事件属性是否有类似的方法?应该捕获事件onload中的任何链接。@奇怪,我已经更新了答案,因为我知道您想单独使用DOMDocument,不想解析原始HTML。请注意,DOM api不能提供您想要的URL-您必须像我一样自己解析字符串建议或以类似方式。在添加的链接中,可以看到几个如何提取属性
onload
的示例。如果我太愚蠢,请原谅,但我的问题本身是如何获取属性“onload”?我已尝试使用getElementsByTagName('body')和,但它的所有节点都没有给出onload=…那么如何获取您提到的第一行?$attribute=“javascript:PopWin(”);没问题——更新了示例
$mathes = array();
preg_match('`(?:.+?)(?<url>https?://[\w\d.&?=]+)(?:.+?)`', $attribute, $matches);

echo $matches['url']; // outputs https://google.com