有没有办法在PHP中,将一段文本中的iframe删除,如果它们不在白名单数组或黑名单数组中的域名中,那么我可以允许像YouTube、Facebook这样的网站的iframe,而不是每个网站。
有没有办法在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>
// 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();
<!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
、body
等标签,那么请在代码末尾运行以下代码...$html = '';
foreach($dom->getElementsByTagName('body')->item(0)->childNodes as $node) {
$html .= $dom->saveXML($node, LIBXML_NOEMPTYTAG);
}
saveXML()
替换为saveHTML()
。
是否可以编辑
$iframe->parentNode->removeChild($iframe);
以替换iframe
?
是的,请使用以下内容替换整个块...
// 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);
saveHTML()
函数接受一个节点作为参数,需要支持 PHP 5.3.6 或更高版本,但你可以尝试一下 :) - alex