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

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

Laravel 5

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

public static function replaceLast(
        $search,
        $replace,
        $subject
    );

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.

use Illuminate\Support\Str;

// Hello! Goodbye!
Str::replaceLast('Hello', 'Goodbye', 'Hello! Hello!');

// Super long content. Another sentence. Final sentence∎
Str::replaceLast(
    '.', '∎',
    'Super long content. Another sentence. Final sentence.'
);

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.

Start the Discussion

Leave a comment

Subscribe to our newsletter