diff --git a/src/Str.php b/src/Str.php index c165a51..fdae7f6 100644 --- a/src/Str.php +++ b/src/Str.php @@ -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 * diff --git a/tests/StrTest.php b/tests/StrTest.php index 5ccb40d..368cc56 100644 --- a/tests/StrTest.php +++ b/tests/StrTest.php @@ -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.*');