Page 1 of 1

[SOLVED] Using variables in replacement pattern

Posted: Thu Mar 22, 2007 9:31 am
by anjanesh

Code: Select all

$s = "[aaa] [bbb] [ccc]";

$x['aaa'] = '111';
$x['bbb'] = '222';
$x['ccc'] = '333';

$r = preg_replace('#\[(.*?)\]#i', '\$x["$1"]', $s);
echo $r;
How do I get 111 222 333 ?

Thanks

Posted: Thu Mar 22, 2007 10:01 am
by Skara
hm... I'm not quite sure what you're needing, but maybe something like this?

Code: Select all

$find = array(
    '#\[aaa\]#i',
    '#\[bbb\]#i',
    '#\[ccc\]#i'
);
$replacement = array(
    '111',
    '222',
    '333'
);
$r = preg_replace($find,$replacement,$s);
Although, in this case, you wouldn't need a regex.

Or something along the lines of...

Code: Select all

function translate($txt) {
    $fix = $txt[0];
    $x = array(
        'aaa' => '111',
        'bbb' => '222',
        'ccc' => '333'
    );
    $out = $x[$fix];
    return $out;
}

$r = preg_replace_callback('#\[(.*?)\]#i','translate',$s);

Re: Using variables in replacement pattern

Posted: Thu Mar 22, 2007 11:51 am
by stereofrog
anjanesh wrote:

Code: Select all

$s = "[aaa] [bbb] [ccc]";

$x['aaa'] = '111';
$x['bbb'] = '222';
$x['ccc'] = '333';

$r = preg_replace('#\[(.*?)\]#i', '\$x["$1"]', $s);
echo $r;
How do I get 111 222 333 ?

Thanks
You're almost there. Just add 'e' modifier to the expression: '#\[(.*?)\]#ie'

Posted: Thu Mar 22, 2007 1:16 pm
by anjanesh
Ah...stereofrog - Thanks a LOT !

Posted: Thu Mar 22, 2007 4:12 pm
by feyd
Be careful when using the "e" modifier. You can walk yourself into dangerous (security compromising) evaluations using it.

preg_replace_callback() is much safer.

Posted: Thu Mar 22, 2007 5:04 pm
by Kieran Huggins
play here: http://www.cuneytyilmaz.com/prog/jrx/

speeds up debugging time A LOT