Skip to content

Instantly share code, notes, and snippets.

@VijayaSankarN
Last active June 18, 2023 14:43
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save VijayaSankarN/0d180a09130424f3af97b17d276b72bd to your computer and use it in GitHub Desktop.
Save VijayaSankarN/0d180a09130424f3af97b17d276b72bd to your computer and use it in GitHub Desktop.
String replace nth occurrence using PHP
<?php
/**
* String replace nth occurrence
*
* @param type $search Search string
* @param type $replace Replace string
* @param type $subject Source string
* @param type $occurrence Nth occurrence
* @return type Replaced string
*/
function str_replace_n($search, $replace, $subject, $occurrence)
{
$search = preg_quote($search);
return preg_replace("/^((?:(?:.*?$search){".--$occurrence."}.*?))$search/", "$1$replace", $subject);
}
@fredrickwampamba
Copy link

Lol, helped me alot. Thank you a lot

@mattneal-stafflink
Copy link

DAMN, thank you.

@mosi2142
Copy link

its good, but the issue is that it doesnt detect new lines

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment