PHP : parse html : extract script tags from body and inject before </body>?

标签 php dom html-content-extraction

我不关心库是什么,但我需要一种方法来从页面的 <.body.> 中提取 <.script.> 元素(作为字符串)。然后我想在 <./body.> 之前插入提取的 <.script.>s。

理想情况下,我想将 <.script.> 提取为两种类型;
1)外部(具有 src 属性的) 2) 嵌入式(代码在<.script.><./script.>之间)

到目前为止,我已经尝试过使用 phpDOM、Simple HTML DOM 和 Ganon。
我对其中任何一个都没有运气(我可以找到链接并删除/打印它们 - 但每次都因脚本而失败!)。

替代
https://stackoverflow.com/questions/23414887/php-simple-html-dom-strip-scripts-and-append-to-bottom-of-body
(很抱歉重新发布,但已经 24 小时尝试并失败,使用替代库,失败更多等等)。


基于来自@alreadycoded.com 的可爱的 RegEx 答案,我设法将以下内容拼凑在一起;

$output = "<html><head></head><body><!-- Your stuff --></body></html>"
$content = '';
$js = '';

// 1) Grab <body>
preg_match_all('#(<body[^>]*>.*?<\/body>)#ims', $output, $body);
$content = implode('',$body[0]);

// 2) Find <script>s in <body>
preg_match_all('#<script(.*?)<\/script>#is', $content, $matches);
foreach ($matches[0] as $value) {
    $js .= '<!-- Moved from [body] --> '.$value;
}

// 3) Remove <script>s from <body>
$content2 = preg_replace('#<script(.*?)<\/script>#is', '<!-- Moved to [/body] -->', $content); 

// 4) Add <script>s to bottom of <body>
$content2 = preg_replace('#<body(.*?)</body>#is', '<body$1'.$js.'</body>', $content2);

// 5) Replace <body> with new <body>
$output = str_replace($content, $content2, $output);

哪个能完成工作,而且不是那么慢(几分之一秒)

遗憾的是,所有 DOM 东西都无法正常工作(或者我不想涉足 naffed 对象并进行操作)。

最佳答案

选择所有具有 src 属性的脚本节点

$xpathWithSrc = '//script[@src]';

选择所有有内容的脚本节点:

$xpathWithBody = '//script[string-length(text()) > 1]';

基本用法(将查询替换为您实际的 xpath 查询):

$doc = new DOMDocument();
$doc->loadHTML($html);

$xpath = new DOMXpath($doc);

foreach($xpath->query('//body//script[string-length(text()) > 1]') as $queryResult) {
    // access the element here. Documentation:
    // http://www.php.net/manual/de/class.domelement.php
}

关于PHP : parse html : extract script tags from body and inject before </body>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23429182/

相关文章:

php - HttpSendRequest 12005 错误

PHP - 读取和写入相同的文件挂起

php - 如果记录存在于 php/PDO 中则删除记录

javascript - 如何复制节点列表?

java - 从java中的网页读取源代码

java - Java 有哪些 HTML 解析库推荐

javascript - 更新/编辑表单,以便它加载从 sql 表中选择的 SELECT 选项值

javascript - 获取 React 组件中子元素的高度

卸载网页后 Javascript 内存泄漏

javascript - 识别网页中的组件使用了哪些 JS 函数和 CSS