Laravel 5 String Helpers: Replacing the Last Occurrence of a Value

December 6, 2017 —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.

#Signature

1public static function replaceLast(
2 $search,
3 $replace,
4 $subject
5 );

#Example Use

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);

#Global str_replace_last Helper Function

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.