preg_replace_callback() could be your friend.
Basic example:
$s="Hello my name is John #last#";
function random_name($m) {
$a=array('Fos', 'Smith', 'Metzdenafbuhrer', 'the Enlightened');
foreach ($m as $match) {
return $a[array_rand($a)];
}
}
$news=preg_replace_callback('/#last#/', 'random_name', $s);
UPDATE: I created another example for you, with more flexibility:
$s="Hello #title#, my name is John #last#";
function random_name($m) {
$a=array(
'last' => array('Fos', 'Smith', 'Metzdenafbuhrer', 'the Enlightened'),
'title' => array('Honey', 'Boss', ', I am your father'),
);
foreach ($m as $match) {
$v=trim($match, '#');
return $a[$v][array_rand($a[$v])];
}
}
$news=preg_replace_callback('/(#[a-z]+#)/', 'random_name', $s);