【问题标题】:Edit iframe content using PHP, and preg_replace()使用 PHP 和 preg_replace() 编辑 iframe 内容
【发布时间】:2017-04-27 16:18:06
【问题描述】:

我需要在我的网站上加载一些第 3 方小部件。他们分发它的唯一方法是通过笨拙的旧<iframe>

我没有太多选择,所以我要做的是获取 iframe html 代码,使用我网站上的代理页面,如下所示:

$iframe = file_get_contents('http://example.com/page_with_iframe_html.php');

然后我必须像这样删除 iframe 中的一些特定部分:

$iframe = preg_replace('~<div class="someclass">[\s\S]*<\/div>~ix', '', $iframe);

通过这种方式,我打算删除不需要的部分。最后我只是像这样输出 iframe:

echo ($iframe);

iframe 可以正常输出,但不需要的部分仍然存在。正则表达式本身使用 regex101 进行了测试,但它不起作用。

【问题讨论】:

  • 使用DOMDocument 来解析HTML 的内容,而不是正则表达式。
  • 您能分享您的HTML 内容吗?
  • @SahilGulati 不是真的,但这里是等价的<div class="someclass"> <span class="hot-line-text"> hotline: </span> <a id="hot-line-tel" class="hot-line-link" href="tel:0000" target="_parent"> <button class="hot-line-button"></button> <span class="hot-line-number">0000</span> </a> </div>
  • 你的预期输出是什么?
  • @SahilGulati 抱歉,上面的代码是我需要删除的代码。输出代码要大得多。我需要做的就是从输出的其余部分中删除我之前评论中的代码

标签: php regex iframe preg-replace domdocument


【解决方案1】:

您应该尝试这种方式,希望这对您有所帮助。这里我使用示例HTML 删除divgiven class name,首先我加载文档,查询并从子节点中删除该节点。

Try this code snippet here

<?php

ini_set('display_errors', 1);
//sample HTML content
$string1='<html>'
        . '<body>'
            . '<div>This is div 1</div>'
            . '<div class="someclass"> <span class="hot-line-text"> hotline: </span> <a id="hot-line-tel" class="hot-line-link" href="tel:0000" target="_parent"> <button class="hot-line-button"></button> <span class="hot-line-number">0000</span> </a> </div>'
        . '</body>'
    . '</html>';

$object= new DOMDocument();
$object->loadHTML($string1);
$xpathObj= new DOMXPath($object);
$result=$xpathObj->query('//div[@class="someclass"]');
foreach($result as $node)
{
    $node->parentNode->removeChild($node);
}
echo $object->saveHTML();

【讨论】:

  • 感谢您让我看到 DOM.so 及其所有便利。这确实是一种渐进的方法。但是我的问题没有解决,查询没有返回任何内容,我在这里打开了新问题stackoverflow.com/questions/43718492/…
猜你喜欢
  • 1970-01-01
  • 2015-09-03
  • 2011-07-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多