Skip to content

Commit

Permalink
Merge pull request #2 from jdecool/string-func
Browse files Browse the repository at this point in the history
Add `startsWith` and `endsWith` methods to Str class
  • Loading branch information
Baptouuuu committed Apr 29, 2019
2 parents d4ebeb0 + bc5a6b7 commit e41bc01
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 0 deletions.
36 changes: 36 additions & 0 deletions src/Str.php
Expand Up @@ -662,6 +662,42 @@ public function contains(string $value): bool
}
}

/**
* Check if the current string starts with the given string
*
* @param string $value
*
* @return bool
*/
public function startsWith(string $value): bool
{
if ($value === '') {
return true;
}

try {
return $this->position($value) === 0;
} catch (SubstringException $e) {
return false;
}
}

/**
* Check if the current string ends with the given string
*
* @param string $value
*
* @return bool
*/
public function endsWith(string $value): bool
{
if ($value === '') {
return true;
}

return (string) $this->takeEnd(self::of($value, $this->encoding)->length()) === $value;
}

/**
* Quote regular expression characters
*
Expand Down
26 changes: 26 additions & 0 deletions tests/StrTest.php
Expand Up @@ -795,6 +795,32 @@ public function testContains()
$this->assertFalse($str->contains('baz'));
}

public function testStartsWith()
{
$str = new S('foobar');

$this->assertTrue($str->startsWith(''));
$this->assertTrue($str->startsWith('foo'));
$this->assertTrue($str->startsWith('foob'));
$this->assertTrue($str->startsWith('foobar'));
$this->assertFalse($str->startsWith('bar'));
$this->assertFalse($str->startsWith('oobar'));
$this->assertFalse($str->startsWith('foobar '));
}

public function testEndsWith()
{
$str = new S('foobar');

$this->assertTrue($str->endsWith(''));
$this->assertTrue($str->endsWith('bar'));
$this->assertTrue($str->endsWith('obar'));
$this->assertTrue($str->endsWith('foobar'));
$this->assertFalse($str->endsWith('foo'));
$this->assertFalse($str->endsWith('fooba'));
$this->assertFalse($str->endsWith('xfoobar'));
}

public function testPregQuote()
{
$a = new S('foo#bar.*');
Expand Down

0 comments on commit e41bc01

Please sign in to comment.