Search code examples
phpregexpreg-replace-callback

Why does this preg_replace_callback not fire?


When I run this script on the second content fragment below, it passes (I get the "inside callback" echo).

However, when I run it on the first content fragment, even thought I get the first echo, I never get the echo inside the p_callback().

I'm guessing that there is something within the content that trips up the preg_replace_callback. What would you suggest is causing the problem?

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;
}

First content fragment fails:

<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>

Second content fragment passes:

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

Solution

  • Your first fragment does not contain <p>...</p>

    Your paragraph tags have attributes.