$replacements = array(
'winnings' => '100'
, 'slice' => '95%'
, 'foobar' => 'Sean Bright'
);
$subject = '[foobar], You will win [winnings] or [slice]!';
$result = preg_replace_callback(
'/\[([^\]]+)\]/',
function ($x) use ($replacements) {
if (array_key_exists($x[1], $replacements))
return $replacements[$x[1]];
return '';
},
$subject);
echo $result;
Note that this will completely fall apart if you have unbalanced brackets (i.e. [[foo]
)
For PHP versions less than 5.3:
$replacements = array(
'winnings' => '100'
, 'slice' => '95%'
, 'foobar' => 'Sean Bright'
);
function do_replacement($x)
{
global $replacements;
if (array_key_exists($x[1], $replacements))
return $replacements[$x[1]];
return '';
}
$subject = '[foobar], You will win [winnings] or [slice]!';
$result = preg_replace_callback(
'/\[([^\]]+)\]/',
'do_replacement',
$subject);
echo $result;