I'm trying to develop a batch find-and-replace for a large text file using preg_replace. I haven't done this before, but I think I basically understand the process. I'm having no trouble doing a straight replacement of x for y. (Numbers 0 and 2 in the arrays below are working fine.) But I can't figure out how to do an insertion that keeps the matched text. I know this should be simple, and I've tried to imitate a bunch of examples.
When I run the code below, the sentence turns into "The Rabbit street mentrance of nighttown." But I'm trying to turn 'Mabbot' into 'MabbotRabbit'. How can I keep the 'Mabbot' in place?
Thank you!
<?php
$content = "The Mabbot street entrance of nighttown";
$patterns = array();
$patterns[0] = '/
/';
$patterns[1] = '/Mabbot/';
$patterns[2] = '/entrance/';
$replacements = array();
$replacements[0] = '<br/>';
$replacements[1] = '$1Rabbit';
$replacements[2] = 'mentrance';
ksort($patterns);
ksort($replacements);
echo preg_replace($patterns, $replacements, $content);
?>
Change
replacements[1] = '$1Rabbit';
to
replacements[1] = '$0Rabbit';
$1
, $2
, and so on get replaced with the match for the Nth capture group, while $0
is replaced with the whole match.