Page 1 of 1

preg_replace help ??

Posted: Tue Jan 20, 2009 4:06 am
by PHPycho
Hello forums!!
Case:

Code: Select all

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

Re: preg_replace help ??

Posted: Tue Jan 20, 2009 4:08 am
by papa
What happens if you use $1 ?

Re: preg_replace help ??

Posted: Tue Jan 20, 2009 4:13 am
by PHPycho
same notice error occurs as:
Undefined index: $1 in

Re: preg_replace help ??

Posted: Tue Jan 20, 2009 4:17 am
by papa
I suck at this but whatta hell:

preg_replace('/\[(.*?)\]/',$db_row['$1'], $string);

Removing the () ?

or

preg_replace('/\[(.*?)\]/',$db_row[$1], $string);

Re: preg_replace help ??

Posted: Tue Jan 20, 2009 4:34 am
by mintedjo

Code: Select all

$db_row[$2]
?

Re: preg_replace help ??

Posted: Tue Jan 20, 2009 4:56 am
by PHPycho
None works.
Any xtra options.
Thanks

Re: preg_replace help ??

Posted: Tue Jan 20, 2009 6:50 am
by Apollo
You can't use $db_row['$2'] as a replacement string just like that. The $2 part would only be replaced after evaluating the array, and since $db_row['$2'] (literally) doesn't exist, you get an empty result.

You need the e regexp modifier, which will evaluate the replacement expression, and put your replacement string in quotes:

Code: Select all

$final_string = preg_replace('/(\[(.*?)\])/e','$db_row["$2"]', $string);
By the way, you can get rid of the outer set of ( ) since they're kinda useless here, and change $2 to $1:

Code: Select all

$final_string = preg_replace('/\[(.*?)\]/e','$db_row["$1"]', $string);
One small sidenote - you probably know this yourself (since you wrote the expression) but for others who may miss this: the ? in (.*?) is to make the * lazy instead of greedy. Without the ? it would catch more characters up to the last ]. So when regexping "[xxx]yyy[zzz]", instead of two parts "xxx" and "zzz", it will find one match: "xxx]yyy[zzz".

Re: preg_replace help ??

Posted: Tue Jan 20, 2009 11:06 am
by PHPycho
Thanks Apollo.
That code is really awsome. and thanks for the hint too.