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