Last active
March 14, 2020 16:08
-
-
Save VijayaSankarN/e5b8017204a83c047410462c96bc3b4b to your computer and use it in GitHub Desktop.
String replace nth occurrence - case-insensitive using PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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