fork download
  1. <?php
  2.  
  3. $subject = "One fish two fish red fish blue fish";
  4.  
  5. function str_replace_nth($search, $replace, $subject, $nth)
  6. {
  7. $found = preg_match_all('/'.preg_quote($search).'/', $subject, $matches, PREG_OFFSET_CAPTURE);
  8. if (false !== $found && $found > $nth) {
  9. return substr_replace($subject, $replace, $matches[0][$nth][1], strlen($search));
  10. }
  11. return $subject;
  12. }
  13.  
  14. echo str_replace_nth('fish', 'bla-bla-bla', $subject, 2);
  15.  
  16.  
Success #stdin #stdout 0.01s 52488KB
stdin
Standard input is empty
stdout
One fish two fish red bla-bla-bla blue fish