0

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?

Nate
  • 26,164
  • 34
  • 130
  • 214
  • Why don't you try `\K`? `$newUrl = preg_replace('#\/foo\/\K([0-9]+)\/#', 4321, $url);` http://regex101.com/r/eF8fY4/2 – Avinash Raj Sep 15 '14 at 02:26
  • 1
    Whats your expected output – hwnd Sep 15 '14 at 02:26
  • @hwnd I'm just wanting to replace the number in the URL, so in this case the expected output would be `http://images.example.com/foo/4321/bar/foobar` – Nate Sep 15 '14 at 02:28
  • Or just with lookarounds, [preg\_replace how to replace only matching xxx($1)yyy pattern inside the selector](http://stackoverflow.com/q/4898192) – mario Sep 15 '14 at 02:29

0 Answers0