From f5f6de7e8a39a879d718385d80a4e869696d9abd Mon Sep 17 00:00:00 2001 From: afsardo Date: Fri, 7 Jul 2017 04:09:18 +0100 Subject: [PATCH] Add the the str_before extra helper, it's the inverse of str_after --- src/Illuminate/Support/Str.php | 22 ++++++++++++++++++++++ src/Illuminate/Support/helpers.php | 14 ++++++++++++++ tests/Support/SupportStrTest.php | 9 +++++++++ 3 files changed, 45 insertions(+) diff --git a/src/Illuminate/Support/Str.php b/src/Illuminate/Support/Str.php index 9e5cb34622c8..a7063d6fff4a 100644 --- a/src/Illuminate/Support/Str.php +++ b/src/Illuminate/Support/Str.php @@ -29,6 +29,28 @@ class Str */ protected static $studlyCache = []; + /** + * Return the remainder of a string before a given value. + * + * @param string $subject + * @param string $search + * @return string + */ + public static function before($subject, $search) + { + if ($search == '') { + return $subject; + } + + $pos = strpos($subject, $search); + + if ($pos === false) { + return $subject; + } + + return substr($subject, 0, $pos); + } + /** * Return the remainder of a string after a given value. * diff --git a/src/Illuminate/Support/helpers.php b/src/Illuminate/Support/helpers.php index 7ec87c5c32ed..9fec8ba3c30b 100755 --- a/src/Illuminate/Support/helpers.php +++ b/src/Illuminate/Support/helpers.php @@ -748,6 +748,20 @@ function starts_with($haystack, $needles) } } +if (! function_exists('str_before')) { + /** + * Return the remainder of a string before a given value. + * + * @param string $subject + * @param string $search + * @return string + */ + function str_before($subject, $search) + { + return Str::before($subject, $search); + } +} + if (! function_exists('str_after')) { /** * Return the remainder of a string after a given value. diff --git a/tests/Support/SupportStrTest.php b/tests/Support/SupportStrTest.php index a50e5650a30c..36ffb0f58653 100755 --- a/tests/Support/SupportStrTest.php +++ b/tests/Support/SupportStrTest.php @@ -88,6 +88,15 @@ public function testEndsWith() $this->assertFalse(Str::endsWith(0.27, '8')); } + public function testStrBefore() + { + $this->assertEquals('han', Str::before('hannah', 'nah')); + $this->assertEquals('ha', Str::before('hannah', 'n')); + $this->assertEquals('ééé ', Str::before('ééé hannah', 'han')); + $this->assertEquals('hannah', Str::before('hannah', 'xxxx')); + $this->assertEquals('hannah', Str::before('hannah', '')); + } + public function testStrAfter() { $this->assertEquals('nah', Str::after('hannah', 'han'));