【问题标题】:Why does this preg_replace_callback not fire? [closed]为什么这个 preg_replace_callback 不触发? [关闭]
【发布时间】:2012-02-17 19:42:06
【问题描述】:

当我在下面的第二个内容片段上运行此脚本时,它通过了(我得到“内部回调”回声)。

但是,当我在第一个内容片段上运行它时,即使我得到了第一个回声,我也从未在 p_callback() 中得到回声。

我猜内容中有些东西会触发 preg_replace_callback。您认为是什么导致了问题?

function ad_insert($content){
    if(substr_count(strtolower($content), '</p>') < get_option('ad_insert') ) 
    {
        return $content .= '<p class="endContent">' . get_ads($ad_insert=1) . '</p>';
    }
    else
    {
    echo "inside else";
    $replaced_content = preg_replace_callback('#(<p>.*?</p>)#', 'p_callback', $content);
    }
    return $replaced_content;
}

function p_callback($matches)
{
    echo "inside callback";die;
    static $count = 0;
    $ret = $matches[1];
    $pCount = get_option('cb2_ad_insert');

    if (++$count == $pCount){
        $ret .= '<p class="insertContent">' . ce4_get_ads($ad_insert=1) . '</p>';
    }

    return $ret;
}

第一个内容片段失败:

<div style="margin: 10px 0;">
    <a href="test.jpg" target="_blank" rel="nofollow">
        <img style="float: left; margin: 10px; max-width: 25%;" title="test" src="test.jpg" alt="test" />
    </a>
    <p style="float: left; width: 70%;">
        <a href="test" target="_blank" rel="nofollow">
            <img title="PDF file" src="test.png" alt="PDF file" /> 
            <span style="font-weight: bold; text-transform: capitalize;">Test ...</span>
        </a>
        <span>test <strong>test</strong> test? test, test, i.e., </span>
        <a href="test.pdf" target="_blank" rel="nofollow"> ... Get Content Here</a>
    </p>
</div>

第二次内容片段传递:

<div style="margin: 10px 0;">
    <p>first paragraph</p>
    <p>second paragraph</p>
</div>

【问题讨论】:

  • 仅显示多数接近投票的原因。我的问题是“这个问题是由一个无法再复制的问题或一个简单的印刷错误引起的。虽然类似的问题可能是这里的主题,但这个问题的解决方式不太可能帮助未来的读者。”

标签: php regex preg-replace-callback


【解决方案1】:

使用s (PCRE_DOTALL) 修饰符:

$replaced_content = preg_replace_callback('#(<p.*?</p>)#s', 'p_callback', $content);
                                                    ____^

【讨论】:

    【解决方案2】:

    您的第一个片段不包含&lt;p&gt;...&lt;/p&gt;

    你的段落标签有属性。

    【讨论】:

    • 谢谢,看来我需要更改匹配正则表达式
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-15
    • 2021-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多