You were very close:
$str = preg_replace('/abc/', '123', $str, 1); // will replace first 'abc'
$str = preg_replace('/abc/', '456', $str); // will replace all others
The reason this will work, is because the 2nd regex's first occurence, is actually the 2nd item.
Pro: Very readable, very easy to understand and implement
Con: the string will be regexed twice (bad for large strings), options are limited
If this is not what you want, you can use preg_replace_callback()
$firstHasBeenFound = false;
function magicFunction($matches){
global $firstHasBeenFound;
print_r($matches);
if( !$firstHasBeenFound ){
/* do something for the first time */ ;
$firstHasBeenFound = true; // save for next round
}
else{
/* do something for the test */ ;
}
}
$str = preg_replace_callback('/abc/', 'magicFunction', $str);
Pro: A lot more variants can be made, more control over code, only one parse of the string
Con: More difficult to read/implement
In this example I use $firstHasBeenFound
, but you could use a increment to do something each 2nd, or something when you find match 7, etc