Skip to content

Commit 31c7c7f

Browse files
bug #394 [Php80] Fix str_ends_with() when needle is longer than haystack (SpacePossum)
This PR was squashed before being merged into the 1.23-dev branch. Discussion ---------- [Php80] Fix str_ends_with() when needle is longer than haystack Little bug, found in PHP-CS-Fixer/PHP-CS-Fixer#6323 https://3v4l.org/oHUKH ```php <?php error_reporting(E_ALL); $needle = '[]'; echo \substr_compare('', $needle, -\strlen($needle)); ``` show issues for ``` Output for 5.3.0 - 5.3.29, 5.4.0 - 5.4.45, 5.5.0 - 5.5.38, 5.6.0 - 5.6.40, 7.0.0 - 7.0.33, 7.1.0 - 7.1.33, 7.2.0 - 7.2.17, 7.3.0 - 7.3.4 Warning: substr_compare(): The start position cannot exceed initial string length in /in/oHUKH on line 4 ``` Looking at the test matrix I assume the tests will run latest 7.2 which is not effected, ~so I naively changed it here in this draft to see if my test indeeds fails on the CI (I don't have an easy 7.2.17 or 7.1.0 env. at hand at the moment)~ @ see shivammathur/setup-php#570 Commits ------- 09a94a5 [Php80] Fix str_ends_with() when needle is longer than haystack
2 parents 329cde9 + 09a94a5 commit 31c7c7f

File tree

3 files changed

+14
-1
lines changed

3 files changed

+14
-1
lines changed

CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
# 1.25.0
22

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

56
# 1.24.0
67

src/Php80/Php80.php

+11-1
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,16 @@ public static function str_starts_with(string $haystack, string $needle): bool
100100

101101
public static function str_ends_with(string $haystack, string $needle): bool
102102
{
103-
return '' === $needle || ('' !== $haystack && 0 === substr_compare($haystack, $needle, -\strlen($needle)));
103+
if ('' === $needle || $needle === $haystack) {
104+
return true;
105+
}
106+
107+
if ('' === $haystack) {
108+
return false;
109+
}
110+
111+
$needleLength = \strlen($needle);
112+
113+
return $needleLength <= \strlen($haystack) && 0 === substr_compare($haystack, $needle, -$needleLength);
104114
}
105115
}

tests/Php80/Php80Test.php

+2
Original file line numberDiff line numberDiff line change
@@ -192,6 +192,8 @@ public function testStrEndsWith()
192192
$testEmoji = '🙌🎉✨🚀'; // 0xf0 0x9f 0x99 0x8c 0xf0 0x9f 0x8e 0x89 0xe2 0x9c 0xa8 0xf0 0x9f 0x9a 0x80
193193
$this->assertTrue(str_ends_with($testEmoji, '🚀')); // 0xf0 0x9f 0x9a 0x80
194194
$this->assertFalse(str_ends_with($testEmoji, '')); // 0xe2 0x9c 0xa8
195+
196+
$this->assertFalse(str_ends_with('', '[]'));
195197
}
196198

197199
/**

0 commit comments

Comments
 (0)