【问题标题】:PHP strip iframe except YouTube with regular expressionPHP 使用正则表达式去除除 YouTube 之外的 iframe
【发布时间】:2014-05-03 02:01:22
【问题描述】:

我想从 HTML 中删除除 YouTube 之外的所有 iframe。

我已经尝试使用插入符号到 YouTube 关键字之外的这段代码,但它不起作用。

$search[] = '@<iframe[^(youtube)]*?>.*?</iframe>@si';
$text = preg_replace($search, '', $document);

【问题讨论】:

  • 为此使用正则表达式非常困难。如果标签是&lt;iframe src="maliciousaddress" decoy="youtube"&gt;&lt;iframe src="maliciousaddress.com/?youtube"&gt; 怎么办?
  • 没关系,因为这个 html 代码来自受信任的来源。这意味着没有恶意代码。我只需要剥离无用的 iframe (facebook) 等...而且我只需要保留 youtube iframe。

标签: php iframe youtube strip


【解决方案1】:

由于谷歌搜索 php strip tags except youtube 将我链接到此处,我想我应该尝试提出替代答案。

也许您想使用像 HTML Purifier 这样的库? Malte 已经在 https://stackoverflow.com/a/12784081/2716927 中提出了这样做的建议。

未经测试的代码,但应该像这样工作:

require_once 'htmlpurifier/library/HTMLPurifier.auto.php';

$config = HTMLPurifier_Config::createDefault();
$config->set('HTML.Trusted', true);
$config->set('HTML.SafeIframe', true);
$config->set('URI.SafeIframeRegexp', '%^(https?:)?//(www\.youtube(?:-nocookie)?\.com/embed/|player\.vimeo\.com/video/)%'); //allow YouTube and Vimeo
$purifier = new HTMLPurifier($config);

$text = $purifier->purify($document);

【讨论】:

  • 对所有人大喊:除非你真的知道自己在做什么,否则不要使用HTML.Trusted
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-08-18
  • 1970-01-01
  • 2013-09-10
  • 1970-01-01
  • 2023-03-10
  • 1970-01-01
  • 2016-01-10
相关资源
最近更新 更多