【问题标题】:PHP: Wrap iframe in div only oncePHP:仅在 div 中包装 iframe 一次
【发布时间】:2018-06-29 03:31:44
【问题描述】:

我刚刚注意到我处理用户故事发布的部分代码没有按应有的方式运行。

每当用户在他的帖子中包含 iframe(例如 YouTube 嵌入视频)时,我的 PHP 脚本都会将 iframe 包装在一个像 <div class="embed-responsive embed-responsive-16by9"> 这样的 div 中。

我使用的代码很简单:

$content = str_replace(['<iframe', '</iframe>'], ['<div class="embed-responsive embed-responsive-16by9"><iframe', '</iframe></div>'], $content);

问题是,当对这篇文章进行更改时,相同的 PHP 代码正在使用 ajax 在后台执行,并且 iframe 再次包装在这个 div 中,这给出了类似这样的内容

<div class="embed-responsive embed-responsive-16by9">
    <div class="embed-responsive embed-responsive-16by9">
        <iframe ...></iframe>
    </div>
</div>

我一直在考虑这个问题,解决方案可能很简单,但是如果 iframe 已经用embed-responsive 类包装在我的 div 中,我该如何检查 PHP?

【问题讨论】:

  • 检查内容是否以&lt;div&gt;开头。如果没有,请添加包装器。
  • 但是$content是整个post内容,所以iframe前后都有标签和文字。如何测试该字符串中 iframe 前面是否有 div?
  • 检查正则表达式,如下所示:/

标签: php html iframe str-replace


【解决方案1】:

如果您将$content 中的现有 iframe 标准化为:

    $content = str_replace(['<div class="embed-responsive embed-responsive-16by9"><iframe', '</iframe></div>'], ['<iframe', '</iframe>'], $content);

$content 中的所有 iframe 现在都将删除其 div 部分。现在执行你已经准备好的str_replace 再次包装 iframe:

    $content = str_replace(['<iframe', '</iframe>'], ['<div class="embed-responsive embed-responsive-16by9"><iframe', '</iframe></div>'], $content);

divparts 已再次添加到框架中,您最终将所有 iframe 仅包装一次。

【讨论】:

    【解决方案2】:

    您可能需要检查 iframe 是否已经有父级。这可以通过在您第一次替换时添加一个类然后将其用作替换中的条件来完成

    if(strpos($content,'class="i-wrapped" ')!== false ){
        //the iframe has not been wrapped
        $content = str_replace(
            ['<iframe', '</iframe>'], 
            ['<div class="embed-responsive embed-responsive-16by9">'.
             '<iframe class="i-wrapped"', '</iframe></div>'],
            $content);
    }else { /*already wrapped*/}
    

    现在对于这样的解决方案有一些注意事项,如果您在帖子中有多个 iFrame,它只会考虑一个 iFrame,此解决方案将失败

    另一种选择可能是计算 iframe 的出现次数,然后以这种方式执行替换

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-06-13
      • 2019-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-16
      相关资源
      最近更新 更多