Skip to content

Commit

Permalink
Add the the str_before extra helper, it's the inverse of str_after
Browse files Browse the repository at this point in the history
  • Loading branch information
afsardo committed Jul 7, 2017
1 parent 5ac005a commit f5f6de7
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 0 deletions.
22 changes: 22 additions & 0 deletions src/Illuminate/Support/Str.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand Down
14 changes: 14 additions & 0 deletions src/Illuminate/Support/helpers.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
9 changes: 9 additions & 0 deletions tests/Support/SupportStrTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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'));
Expand Down

0 comments on commit f5f6de7

Please sign in to comment.