When using preg_replace()
, is it possible to only replace a matching group in "()" instead of replacing everything in the pattern parameter?
For example, consider this URL:
$url = 'http://images.example.com/foo/1234/bar/foobar';
To replace the number with another one, I tried doing this:
$newUrl = preg_replace('#\/foo\/([0-9]+)\/#', 4321, $url);
But the result is this:
http://images.example.com4321bar/foobar
So it appears that preg_replace()
replaces everything in the pattern parameter instead of just the matching group.
Is there any way to only replace the matching group instead of replacing everything in the pattern parameter?