How to use PHP preg_replace regex to find and replace text?

I wrote this PHP code to make some replacements:

function cambio($txt){
    $from=array(
        '/\+\>([^\+\>]+)\<\+/', //finds +>text<+
        '/\%([^\%]+)\%/',   //finds %text%
    );

    $to=array(
        '<span class="P">\1</span>',
        '<span>\1</span>',
    );

    return preg_replace($from,$to,$txt);
}

echo cambio('The fruit I most like is: +> %apple% %banna% %orange% <+.');

As a result:

The fruit I most like is: <span class="P"> <span>apple</span> <span>banna</span> <span>orange</span> </span>.

However, I needed to identify the fruit range tags, for example:

The fruit I most like is: <span class="P"> <span class="t1">apple</span> <span class="t2">banana</span> <span class="t3">coco</span> </span>.

I would buy fruit for which you can find a regular expression for this :-)


Helping Xavier Barbosa, I came to this final resolution:

function matches($matches){
    static $pos=0;
    return sprintf('<span class="t%d">%s</span>',++$pos,$matches[1]);
}

function cambio($txt){//Markdown da Atípico : Deve ser usado depois do texto convertido para markdown
    $from=array(
        '/\=>(.+?)<\=/', //finds: =>text<=
        '/\+>(.+?)<\+/', //finds +>text<+
    );

    $to=array(
        '<span class="T">\1</span>',
        '<span class="P">\1</span>',
    );

    $r=preg_replace($from,$to,$txt);
    return preg_replace_callback('/%(.*?)%/','matches',$r);//finds %text%
    //'/%((\w)\w+)%/'   //option
}
+5
source share
2 answers
<?php


function cambio($txt){
    $from=array(
        '/\+>(.+?)<\+/', //finds +>text<+
        '/%((\w)\w+)%/',   //finds %text%
    );

    $to=array(
        '<span class="P">\1</span>',
        '<span class="\2">\1</span>',
    );

    return preg_replace($from,$to,$txt);
}

echo cambio('The fruit I most like is: +> %apple% %banna% %orange% <+.');

And the stateful version for PHP5.3

function cambio($txt) {
    return preg_replace_callback('/\+>(.+?)<\+/', function ($matches) {
        $txt = sprintf('<span class="P">%s</span>', $matches[1]);

        return preg_replace_callback('/%(\w+)%/', function ($matches) {
            static $pos = 0;
            return sprintf('<span class="t%d">%s</span>', ++$pos, $matches[1]);
        }, $txt);

    }, $txt);
}

echo  cambio('The fruit I most like is: +> %apple% %banna% %orange% <+.');
+2
source

Try the following:

function cambio($txt){
    $from=array(
        '/\+\>([^\+\>]+)\<\+/', //finds +>text<+
        '/\%(^\%)([^\%]+)\%/',   //finds %text%
    );

    $to=array(
        '<span class="P">\1</span>',
        '<span class="\1">\1\2</span>',
    );

    return preg_replace($from,$to,$txt); }

echo cambio('The fruit I most like is:
+> %apple% %banna% %orange% <+.');
+1
source

All Articles