Posted in Code Snippets, PHP

String replace nth occurrence

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, call str_replace_n with a fourth parameter for occurrence.

Example:

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:

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s