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

December 6, 2017 —John Koster

The replaceFirst helper method is used to replace the first 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

The signature of the replaceMethod is:

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

#Example Use

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

1use Illuminate\Support\Str;
2 
3// //maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css
4Str::replaceFirst(
5 'http://', '//',
6 'http://maxcdn.bootstrapcdn.com/bootstrap/' .
7 '3.3.6/css/bootstrap.min.css'
8);
9 
10// Hello, there!
11Str::replaceFirst('there', 'Hello', 'there, there!');

#Global str_replace_first Helper Function

The str_replace_first function is a shortcut to calling Str::replaceFirst. 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.