So firstly you check if there is any occurrence and if so, you replace it. You could count the occurrences (unsing substr_count) instead to know how many of them exist. Then, just replace them bit by bit if that's what you need.
$occurrences = substr_count($routeName, '/nl/');
if ($occurrences > 0) {
$routeName = preg_replace('/nl/', $lang , $routeName, 1 );
if ($occurrences > 1) {
// second replace
$routeName = preg_replace('/nl/', $lang , $routeName, 1 );
}
}
If you only want to replace the second occurrence (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 occurrence, found using strpos
as a start for substr and just use that for your replacement.
<?php
$routeName = 'http://example.nl/language/nl/peter-list/foo/bar?example=y23&source=nl';
$lang = 'de';
$routeNamePart1 = substr( $routeName, 0 , strpos($routeName,'nl') +4 );
$routeNamePart2 = substr( $routeName, strpos($routeName,'nl') + 4);
$routeNamePart2 = preg_replace('/nl/', $lang , $routeNamePart2, 1 );
$routeName = $routeNamePart1 . $routeNamePart2;
echo $routeName;
See this working here.