gpt4 book ai didi

php - 仅允许来自某些网站的 iframe

转载 作者:行者123 更新时间:2023-12-03 03:22:15 24 4
gpt4 key购买 nike

有谁知道 php 中的一种方法可以获取一段文本并删除 iframe(如果它们不是来自白名单数组或黑名单数组中的域)?所以我可以允许来自 YouTube、Facebook 等的 iframe,但不是每个网站。

最佳答案

输入

<h3>Allowed</h3>
<iframe src="http://youtube.com" ></iframe>
<iframe src="http://www.facebook.com" ></iframe>
<iframe src="http://google.com" ></iframe>

<h3>Banned</h3>
<iframe src="http://example.com" ></iframe>
<iframe src="http://alexanderdickson.com" ></iframe>

PHP

// Make a list of allows hosts.
$allowedHosts = array(
'youtube.com',
'facebook.com',
'google.com'
);

$dom = new DOMDocument;
$dom->loadHTML($str);

// Get all iframes in the document.
$iframes = $dom->getElementsByTagName('iframe');
$iframesLength = $iframes->length;

// Iterate over all iframes.
while ($iframesLength--) {
$iframe = $iframes->item($iframesLength);
if ($iframe->hasAttribute('src')) {

// Get the src attribute of the iframe.
$src = $iframe->getAttribute('src');

// Get the host of this iframe, to compare with our allowed hosts.
$host = parse_url($src, PHP_URL_HOST);

// If not host, then skip this iframe.
if ($host === NULL) {
continue;
}

// Strip www. because otherwise it may be 'www.facebook.com` and we have only
// banned `facebook.com`.
$host = preg_replace('/^www\./', '', $host);


// If this host is not in our allowed list, remove it from the document.
if ( ! in_array($host, $allowedHosts)) {
$iframe->parentNode->removeChild($iframe);
}
}
}
echo $dom->saveHTML();

CodePad .

输出

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"> 
<html><body>
<h3>Allowed</h3>
<iframe src="http://youtube.com"></iframe>
<iframe src="http://www.facebook.com"></iframe>
<iframe src="http://google.com"></iframe>

<h3>Banned</h3>

</body></html>

如果您不希望返回的 HTML 包含在所有 htmlbody 等中,请在最后运行此代码...

$html = '';
foreach($dom->getElementsByTagName('body')->item(0)->childNodes as $node) {
$html .= $dom->saveXML($node, LIBXML_NOEMPTYTAG);
}

如果您的版本 >= PHP 5.3.6,请替换 saveXML()上面有 saveHTML() .

更新

Would it be possible to edit $iframe->parentNode->removeChild($iframe); to replace the iframe?

是的,将整个 block 替换为...

// Create video element
$video = $dom->createElement('video');

// Attach whatever you need to...
$video->setAttribute('src', 'whatever');

// Get a reference to the parent of the iframe
$parent = $iframe->parentNode;

// Insert the video element before the iframe
$parent->insertBefore($video, $iframe);

// Remove the iframe
$parent->removeChild($iframe);

关于php - 仅允许来自某些网站的 iframe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5347665/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com