Created
February 24, 2016 16:35
-
-
Save vlakoff/9269ea56b3c305575ff3 to your computer and use it in GitHub Desktop.
Add Str::replaceFirst, replaceLast and corresponding helpers to Laravel 5.1 LTS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use Illuminate\Support\Str; | |
Str::macro('replaceFirst', function ($search, $replace, $subject) { | |
$position = strpos($subject, $search); | |
if ($position !== false) { | |
return substr_replace($subject, $replace, $position, strlen($search)); | |
} | |
return $subject; | |
}); | |
Str::macro('replaceLast', function ($search, $replace, $subject) { | |
$position = strrpos($subject, $search); | |
if ($position !== false) { | |
return substr_replace($subject, $replace, $position, strlen($search)); | |
} | |
return $subject; | |
}); | |
if (! function_exists('str_replace_first')) { | |
function str_replace_first($search, $replace, $subject) | |
{ | |
return Str::replaceFirst($search, $replace, $subject); | |
} | |
} | |
if (! function_exists('str_replace_last')) { | |
function str_replace_last($search, $replace, $subject) | |
{ | |
return Str::replaceLast($search, $replace, $subject); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment