Laravel String Helper Function: str_replace_last

November 16, 2016 —John Koster

The replaceLast helper method is the logical opposite of the replaceFirst helper method. It is used to replace the last occurrence of a given $search string with the provided $replace string in the $subject string. ALl three parameters are required and must be strings.

The signature for the replaceLast helper method is:

replaceLast($search, $replace, $subject)

The following examples highlight the basic usage of the replaceLast method. The results of the method call will appear above the call as a comment.

1use Illuminate\Support\Str;
2 
3// Hello! Goodbye!
4Str::replaceLast('Hello', 'Goodbye', 'Hello! Hello!');
5 
6// Super long content. Another sentence. Final sentence∎
7Str::replaceLast(
8 '.', '∎',
9 'Super long content. Another sentence. Final sentence.'
10);

#str_replace_last($search, $replace, $subject)

The str_replace_last function is a shortcut to calling Str::replaceLast. This function is declared in the global namespace.

Some absolutely amazing
people

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.