I want to ask if it's possible to use a matched regex pattern in determining the replacement from an array. For example
$rpl['brat'] = 'qwerty';
$rpl['omri'] = 'asdfgh';
$str1 = 'abc brat bca';
$str2 = 'abc omri bca';
print_r(preg_replace('#bc (.+?) bc#'), $rpl[$1], $str1)); // aqwertya
print_r(preg_replace('#bc (.+?) bc#'), $rpl[$1], $str2)); // aasdfgha
Now obviously $1
is incorrect syntax, but this is just to show the point I'm making. How can I do this?
Using preg_replace_callback
with modified regular expression:
$rpl['brat'] = 'qwerty';
$rpl['omri'] = 'asdfgh';
$str1 = 'abc brat bca';
$str2 = 'abc omri bca';
print_r(preg_replace_callback('/bc (\w+) bc/', function($match) use($rpl) {
return $rpl[$match[1]];
}, $str1)); // => abc qwerty bca
print_r("
");
print_r(preg_replace_callback('/bc (\w+) bc/', function($match) use($rpl) {
return $rpl[$match[1]];
}, $str1)); // => aqwertya
output:
abc qwerty bca
aqwertya
also you can use flag 'e' , but that is NOT recommended because of it may cause secure problem
print_r(preg_replace('/bc (.+?) bc/e', '$rpl[$1]', $str1));
print_r(preg_replace('/bc (.+?) bc/e', '$rpl[$1]', $str2));