Skip to content

Instantly share code, notes, and snippets.

@VijayaSankarN
Last active March 14, 2020 16:08
Show Gist options
  • Save VijayaSankarN/e5b8017204a83c047410462c96bc3b4b to your computer and use it in GitHub Desktop.
Save VijayaSankarN/e5b8017204a83c047410462c96bc3b4b to your computer and use it in GitHub Desktop.
String replace nth occurrence - case-insensitive using PHP
<?php
/**
* String replace nth occurrence - case-insensitive
*
* @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_ireplace_n($search, $replace, $subject, $occurrence)
{
$search = preg_quote($search);
return preg_replace("/^((?:(?:.*?$search){".--$occurrence."}.*?))$search/i", "$1$replace", $subject);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment