views:

33

answers:

1

I have a Joomla plugin (not important in this context), which is designed to take an input with a load of numbers (within a paragraph of text) and replace them with a series of s.

My problem is that I need to do a preg_replace on my $article->text, but I don't know how to then apply the changes to the matched terms. I've seen the preg_replace_callback, but I don't know how I can call that within a function.

function onPrepareContent( &$article, &$params, $limitstart )
    {
        global $mainframe;
        // define the regular expression
        $pattern = "#{lotterynumbers}(.*?){/lotterynumbers}#s";
        if(isset($article->text)){
            preg_match($pattern, $article->text, $matches);
            $numbers = explode("," , $matches[1]);
            foreach ($numbers as $number) {
                echo "<div class='number'><span>" . $number . "</span></div>";  
            }
        }else{
            $article->text = 'No numbers';
        }
        return true;
    }

AMENDED CODE:

function onPrepareContent( &$article, &$params, $limitstart )
    {
        global $mainframe;
        // define the regular expression
        $pattern = "#{lotterynumbers}(.*?){/lotterynumbers}#s";
        if(isset($article->text)){
            preg_match($pattern, $article->text, $matches);
            $numbers = explode("," , $matches[1]);
            foreach ($numbers as $number) {
                $numberlist[] = "<div class='number'><span>" . $number . "</span></div>";   
            }
            $numberlist = implode("", $numberlist);
            $article->text = preg_replace($pattern, $numberlist, $article->text);

        }else{
            $article->text = 'No numbers';
        }
        return true;
    }
+1  A: 
function onPrepareContent( &$article, &$params, $limitstart )
{
    global $mainframe;
    // define the regular expression
    $pattern = "#{lotterynumbers}(.*?){/lotterynumbers}#s";
    if(isset($article->text)){
        $article->text=preg_replace_callback($pattern,create_function('$match','$init="<div class=\'number\'><span>";$out="</span></div>"; return $init.implode($out.$init,explode(",",$match[1])).$out;'),$article->text);

    }else{
        $article->text = 'No numbers';
    }
    return true;
}

I've not tested it but it should work

mck89
Thanks mck89. I've credited you with the answer, though both methods work. It's a case of maintainability/readability vs technical solution. Useful for reference in either case.Pete
Jeepstone