Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add the the str_before extra helper, it's the inverse of str_after #19940

Merged
merged 1 commit into from
Jul 7, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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