We can replace every occurrence of character or a string using str_replace. But to replace only a specific nth occurrence, we need a small work around:
This short snippet will just replace nth occurrence of a character or string. As we call
str_replace_n with a fourth parameter for occurrence.
echo str_replace_n("t","b","This is a test string with five t's",2); // This is a tesb string with five t's
echo str_replace_n("test","real","This is a test string with five t's",1); // This is a real string with five t's
For case-insensitive replace, just use
str_ireplace_n with the following snippet: