Skip to content

Commit

Permalink
[Php80] Fix str_ends_with() when needle is longer than haystack
Browse files Browse the repository at this point in the history
  • Loading branch information
SpacePossum authored and nicolas-grekas committed Mar 4, 2022
1 parent 329cde9 commit 09a94a5
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# 1.25.0

* Add `PhpToken` to the PHP 8.0 polyfill when the tokenizer extension is enabled
* Fix `str_ends_with()` when needle is longer than haystack

# 1.24.0

Expand Down
12 changes: 11 additions & 1 deletion src/Php80/Php80.php
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,16 @@ public static function str_starts_with(string $haystack, string $needle): bool

public static function str_ends_with(string $haystack, string $needle): bool
{
return '' === $needle || ('' !== $haystack && 0 === substr_compare($haystack, $needle, -\strlen($needle)));
if ('' === $needle || $needle === $haystack) {
return true;
}

if ('' === $haystack) {
return false;
}

$needleLength = \strlen($needle);

return $needleLength <= \strlen($haystack) && 0 === substr_compare($haystack, $needle, -$needleLength);
}
}
2 changes: 2 additions & 0 deletions tests/Php80/Php80Test.php
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,8 @@ public function testStrEndsWith()
$testEmoji = 'πŸ™ŒπŸŽ‰βœ¨πŸš€'; // 0xf0 0x9f 0x99 0x8c 0xf0 0x9f 0x8e 0x89 0xe2 0x9c 0xa8 0xf0 0x9f 0x9a 0x80
$this->assertTrue(str_ends_with($testEmoji, 'πŸš€')); // 0xf0 0x9f 0x9a 0x80
$this->assertFalse(str_ends_with($testEmoji, '✨')); // 0xe2 0x9c 0xa8

$this->assertFalse(str_ends_with('', '[]'));
}

/**
Expand Down

0 comments on commit 09a94a5

Please sign in to comment.