php/regex: How to replace part of a found pattern, but leaving the rest as it is?
If your regex matches only the relevant part, it should be no problem that it replaces the complete match (like preg_replace('/X/', 'Z', $string)
).
But if you need the regex to contain parts that should not be replaced, you need to capture them and insert them back:
preg_replace('/(non-replace)X(restofregex)/', '$1Z$2', $string);
If it's really as simple as replacing X
with Z
, you can also use str_replace()
, which is faster than using preg
in this case:
$sNew = str_replace("X", "Z", $sOld);
Try this
<?php
$string = 'The quick brown fox jumped over the lazy dog.';
$patterns[0] = '/quick/';
$patterns[1] = '/brown/';
$patterns[2] = '/fox/';
$replacements[2] = 'bear';
$replacements[1] = 'black';
$replacements[0] = 'slow';
echo preg_replace($patterns, $replacements, $string);
?>
The above example will output:
The bear black slow jumped over the lazy dog.