Here is what I did to make the replacement:
$new_digit = 1978;
$url = 'http://example.com/s/192090/1/text';
print "Original URL: ".$url;
$url = preg_replace('~s/\d+/\K\d+(?=/)~', $new_digit, $url);
print "\n New URL: ".$url;
This outputs:
Original URL: http://example.com/s/192090/1/text
New URL: http://example.com/s/192090/1978/text
Here is the explanation of the REGEX:
s/ \d+/ \K \d+ (?=/)
^ ^ ^ ^ ^
1 2 3 4 5
s/
This is an anchor point and not really necessary. You can start the expression with the second item and still get the same thing. I put it in there because I wanted to show some sort of anchor.
\d+/
Here, we are looking for one or more digits followed by a forward slash.
\K
This tells the Regular Expression to start over from here. Now that we've made a successful match up to this point, we want to pull out everything after this. (We made a match, but we don't want to capture it, we just to note its location so we know where to start replacing from.
\d+
One or more digits. This is the only part of the expression that will actually be captured. Consequently, this is the only part of the expression that will be replaced.
(?=/)
This is a lookahead to find the slash after the digits it captured. Lookaheads are not captured and all this really does is set the ending for the \d+
. Since the slash is not a digit, it will not be matched by the \d+
and it is not really necessary here either. I'm solely using it to show an anchor. The expression would work just fine without it.
Without the unnecessary anchors (items 1 & 5), you could prune the expression down to this if you wanted:
~\d+/\K\d+~
And still get the same results.
Here is a working demo