我剛剛讀了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