无法让 preg_replace 工作

Can't get preg_replace to work

我希望我刚刚犯了一个简单的错误,您可以帮助纠正。不幸的是,我对 PHP.

不是很有经验

我正在尝试 运行 两个正则表达式覆盖一个字符串。

您会注意到第一个尝试定位脚本和 iframe,然后用 div 包裹它。

第二个,只是试图用 HTTP 协议替换“//”URL - 我意识到这个可以作为 str_replace 来完成,我在下面注释掉了。我测试了 str_replace 正在努力确保没有任何有趣的事情没有被调用,并且它工作正常。由于某种原因,preg_replace 基本上被忽略并且字符串未更改。

我是不是漏掉了什么明显的东西?

我尝试了几个在线 preg_replace 工具,它们似乎是正确的。

function cleanseSpringboardEmbed($content)
{
    // run regex over the content to clean up the embed code from springboard and make compatible with IA.
    $patternWrapper = '/<script src="\/\/www.springboardplatform\.com\/js\/overlay"><\/script><iframe(.*)<\/iframe>/';

    $patternProtocol = '/<iframe src="\/\/cms.springboardplatform.com/';

    $holder = $content;

    $replacementWrapper = '<figure class="op-interactive">' . '[=11=]' . '</figure>';
    $replacementProtocol = '<iframe src="http://cms.springboardplatform.com';

    //$holder = str_replace("//cms.springboardplatform.com","http://cms.springboardplatform.com", $holder);
    //$holder = str_replace("//www.springboardplatform.com","http://www.springboardplatform.com", $holder);

    preg_replace($patternWrapper, $replacementWrapper, $holder);
    preg_replace($patternProtocol, $replacementProtocol, $holder);
    return $holder;
}

这是一些输入的示例

<p>test<br />
<script src="//www.springboardplatform.com/js/overlay"></script><iframe id="crzy003_1621795" src="//cms.springboardplatform.com/embed_iframe/5365/video/1621795/crzy003/craziestsportsfights.com/10" width="600" height="400" frameborder="0" scrolling="no"></iframe><br />
test</p>

您在执行 preg_replace 后忘记分配修改后的 holder 值。根据上面的手册页

preg_replace() returns an array if the subject parameter is an array, or a string otherwise.

If matches are found, the new subject will be returned, otherwise subject will be returned unchanged or NULL if an error occurred.

因此您应该将代码修改为:

<?php

function cleanseSpringboardEmbed($content)
{
    // run regex over the content to clean up the embed code from springboard and make compatible with IA.
    $patternWrapper = '/<script src="\/\/www.springboardplatform\.com\/js\/overlay"><\/script><iframe(.*)<\/iframe>/';

    $patternProtocol = '/<iframe src="\/\/cms.springboardplatform.com/';

    $holder = $content;

    $replacementWrapper = '<figure class="op-interactive">' . '[=10=]' . '</figure>';
    $replacementProtocol = '<iframe src="http://cms.springboardplatform.com';

    //$holder = str_replace("//cms.springboardplatform.com","http://cms.springboardplatform.com", $holder);
    //$holder = str_replace("//www.springboardplatform.com","http://www.springboardplatform.com", $holder);

    $holder = preg_replace($patternWrapper, $replacementWrapper, $holder);
    $holder = preg_replace($patternProtocol, $replacementProtocol, $holder);
    return $holder;
}