[SOLVED] Using variables in replacement pattern

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
User avatar
anjanesh
DevNet Resident
Posts: 1679
Joined: Sat Dec 06, 2003 9:52 pm
Location: Mumbai, India

[SOLVED] Using variables in replacement pattern

Post 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
Last edited by anjanesh on Thu Mar 22, 2007 1:17 pm, edited 1 time in total.
User avatar
Skara
Forum Regular
Posts: 703
Joined: Sat Mar 12, 2005 7:13 pm
Location: US

Post 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);
User avatar
stereofrog
Forum Contributor
Posts: 386
Joined: Mon Dec 04, 2006 6:10 am

Re: Using variables in replacement pattern

Post 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'
User avatar
anjanesh
DevNet Resident
Posts: 1679
Joined: Sat Dec 06, 2003 9:52 pm
Location: Mumbai, India

Post by anjanesh »

Ah...stereofrog - Thanks a LOT !
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post 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.
User avatar
Kieran Huggins
DevNet Master
Posts: 3635
Joined: Wed Dec 06, 2006 4:14 pm
Location: Toronto, Canada
Contact:

Post by Kieran Huggins »

play here: http://www.cuneytyilmaz.com/prog/jrx/

speeds up debugging time A LOT
Post Reply