Forum Moderators: coopster

Message Too Old, No Replies

preg replace help ?

         

PHPycho

10:06 am on Jan 20, 2009 (gmt 0)

10+ Year Member



Hello forums!
Case:
$db_row = array('name_field' => 'Tom', 'roll_field' => 22) ; //items from db

$string = 'my/name/[name_field]/roll/[roll_field]';

$final_string = preg_replace('/(\[(.*?)\])/',$db_row['$2'], $string); //I tried this, but gives notice error: Undefined index: $2

echo $final_string; // expected output: my/name/Tom/roll/22

How to accomplish this using preg_replace.
Thanks.

enigma1

12:52 pm on Jan 20, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



You don't even need the preg_replace I think.

$db_row = array('name_field' => 'Tom', 'roll_field' => 22) ; //items from db

$tmp_array = array('0' => 'my', '1' => 'name');
$tmp_array = array_merge($tmp_array, $db_row);
echo implode('/', $tmp_array);

Also if you don't need the array keys you could drop them, makes the code simpler.

PHPycho

5:27 pm on Jan 20, 2009 (gmt 0)

10+ Year Member



Here is the awsome solution found so far:
<?php
$db_row = array('name_field' => 'Tom', 'roll_field' => 22) ; //items from db

$string = 'my/name/[name_field]/roll/[roll_field]';

$final_string = preg_replace('/\[(.*?)\]/e','$db_row["$1"]', $string); //I tried this, but gives notice error: Undefined index: $2

echo $final_string; // expected output: my/name/Tom/roll/22
?>
Are there any alternatives ?
Thanks

coopster

11:35 pm on Jan 21, 2009 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



There's usually always more than one way to accomplish a task but if that is working without issue, go with it! It was the "e" modifier you needed in your pattern. That, and the correct subpattern variable number :)