This is what I do now:
if (strpos($routeName,'/nl/') !== false) {
$routeName = preg_replace('/nl/', $lang , $routeName, 1 );
}
I replace the nl
with for ex. de
. But now I want to replace the second occurrence
. What's the easiest way to do this?
The answer by @Casimir seems rather applicable to most cases. Another alternative is
preg_replace_callback
with a counter. In case you need a specific n-th occurence to be replaced only.This utilizes a local
$counter
, incremented within the callback on each occurence, and there simply checked for a fixed position here.So firstly you check if there is any occurance and if so, you replace it. You could count the occurances (unsing substr_count) instead to know how many of them exist. Then, just replace them bit by bit if that's what you need.
If you only want to replace the second occurance (as stated by you later on in the comments), check out substr and read up on string functions in PHP. You can use the first occurance, found using
strpos
as a start for substr and just use that for your replacement.See this working here.
You can do that:
\K
will remove all on the left from match result.(Thus, all that has been matched on the left with by/nl/.*?(?<=/)
will not be replaced.)I use a lookbehind
(?<=/)
instead of a literal/
to deal with this specific case/nl/nl/
(In this case.*?
matches an empty substring.)