无法使preg_replace工作

时间:2016-04-14 04:02:43

标签: php regex wordpress preg-replace

我希望我犯了一个简单的错误,你可以帮忙纠正。不幸的是,我对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">' . '$0' . '</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>

1 个答案:

答案 0 :(得分:1)

执行preg_replace后,您忘记分配已修改的持有人值。根据上面的手册页

  如果subject参数是一个数组,

preg_replace()返回一个数组,   否则就是一个字符串。

     

如果找到匹配项,则返回新主题,否则返回   如果发生错误,主题将保持不变或NULL

所以你应该修改你的代码:

<?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">' . '$0' . '</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;
}