我刚刚读了this blog entry,并成功创建并使用了自定义过滤器。我做了一些修改的代码,增加了Vimeo的支持:
/**
* Based on: http://sachachua.com/blog/2011/08/drupal-html-purifier-embedding-iframes-youtube/
* Iframe filter that does some primitive whitelisting in a somewhat recognizable and tweakable way
*/
class HTMLPurifier_Filter_MyIframe extends HTMLPurifier_Filter
{
public $name = 'MyIframe';
/**
*
* @param string $html
* @param HTMLPurifier_Config $config
* @param HTMLPurifier_Context $context
* @return string
*/
public function preFilter($html, HTMLPurifier_Config $config, HTMLPurifier_Context $context)
{
$html = preg_replace('#<iframe#i', '<img class="MyIframe"', $html);
$html = preg_replace('#</iframe>#i', '</img>', $html);
return $html;
}
/**
*
* @param string $html
* @param HTMLPurifier_Config $config
* @param HTMLPurifier_Context $context
* @return string
*/
public function postFilter($html, HTMLPurifier_Config $config, HTMLPurifier_Context $context)
{
$post_regex = '#<img class="MyIframe"([^>]+?)>#';
return preg_replace_callback($post_regex, array($this, 'postFilterCallback'), $html);
}
/**
*
* @param array $matches
* @return string
*/
protected function postFilterCallback($matches)
{
// Domain Whitelist
$youTubeMatch = preg_match('#src="https?://www.youtube(-nocookie)?.com/#i', $matches[1]);
$vimeoMatch = preg_match('#src="http://player.vimeo.com/#i', $matches[1]);
if ($youTubeMatch || $vimeoMatch) {
$extra = ' frameborder="0"';
if ($youTubeMatch) {
$extra .= ' allowfullscreen';
} elseif ($vimeoMatch) {
$extra .= ' webkitAllowFullScreen mozallowfullscreen allowFullScreen';
}
return '<iframe ' . $matches[1] . $extra . '></iframe>';
} else {
return '';
}
}
}
添加过滤器到你的HTML过滤配置
$config->set('Filter.Custom', array(new HTMLPurifier_Filter_MyIframe()));
iframe中仍然受阻反正没梅特。你知道另一个好的解决方案,但支持iframe吗? – swamprunner7 2011-01-19 21:14:53
哦,是的,你将不得不单独添加Iframe支持。以下是一种可能的方式:http://htmlpurifier.org/phorum/read.php?3,4646,4646#msg-4646当然,我们希望(最终)在核心中正确添加对它的支持。 – 2011-01-19 22:00:53
我试过这个解决方案,但我有问题,这里是我的最后一个评论http://stackoverflow.com/questions/4135755/how-do-i-allow-script-object-param-embed-and-iframe-tags-in -htmlpurifier – swamprunner7 2011-01-19 23:13:41