如何使用PHP preg_replace正则表达式来查找和替换文本?

时间:2011-01-13 19:36:56

标签: php regex

我写了这个PHP代码来做一些替换:

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% <+.');

导致:

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

但是我需要识别水果的span标签,如下所示:

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

我会买一种能找到正则表达式的水果来实现这个目标: - )


在Xavier Barbosa的帮助下,我来到最后的解决方案:

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
}

2 个答案:

答案 0 :(得分:2)

<?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% <+.');

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% <+.');

答案 1 :(得分:1)

试试这个:

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% <+.');