I am trying to replace the words in a sentence using preg_replace_callback
.
"%1% and %2% went up the %3%"
should become
"Jack and Jill went up the hill"
I have given my code below.
<?php
$values = array("Jack", "Jill", "hill");
$line = "%1% and %2% went up the %3%";
$line = preg_replace_callback(
'/%(.*?)%/',
create_function(
// single quotes are essential here,
// or alternative escape all $ as \$
'$matches',
'return $values[$matches[1]-1];'
),
$line
);
echo $line;
?>
What I am getting is
" and went up the "
If I give return $matches[1]-1;
, I am getting
"0 and 1 went up the 2"
Is it a scope issue ? How to make this working ? Any help would be appreciated.