Last active
June 18, 2023 14:43
-
-
Save VijayaSankarN/0d180a09130424f3af97b17d276b72bd to your computer and use it in GitHub Desktop.
String replace nth occurrence 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 | |
* | |
* @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); | |
} |
DAMN, thank you.
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
Lol, helped me alot. Thank you a lot