Skip to content

Commit 1373690

Browse files
committed
General: Backport polyfills for str_ends_with() and str_starts_with().
Merges [52040], [56016], and [56015] to 4.3 branch. Props ocean90, SergeyBiryukov, desrosj, joemcgill, jorbin, mukesh27. git-svn-id: https://develop.svn.wordpress.org/branches/4.3@57440 602fd350-edb4-49c9-b593-d223f7449a82
1 parent eef28c2 commit 1373690

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

src/wp-includes/compat.php

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -260,3 +260,49 @@ function hash_equals( $a, $b ) {
260260
if ( ! defined( 'JSON_PRETTY_PRINT' ) ) {
261261
define( 'JSON_PRETTY_PRINT', 128 );
262262
}
263+
264+
if ( ! function_exists( 'str_starts_with' ) ) {
265+
/**
266+
* Polyfill for `str_starts_with()` function added in PHP 8.0.
267+
*
268+
* Performs a case-sensitive check indicating if
269+
* the haystack begins with needle.
270+
*
271+
* @since 5.9.0
272+
*
273+
* @param string $haystack The string to search in.
274+
* @param string $needle The substring to search for in the `$haystack`.
275+
* @return bool True if `$haystack` starts with `$needle`, otherwise false.
276+
*/
277+
function str_starts_with( $haystack, $needle ) {
278+
if ( '' === $needle ) {
279+
return true;
280+
}
281+
282+
return 0 === strpos( $haystack, $needle );
283+
}
284+
}
285+
286+
if ( ! function_exists( 'str_ends_with' ) ) {
287+
/**
288+
* Polyfill for `str_ends_with()` function added in PHP 8.0.
289+
*
290+
* Performs a case-sensitive check indicating if
291+
* the haystack ends with needle.
292+
*
293+
* @since 5.9.0
294+
*
295+
* @param string $haystack The string to search in.
296+
* @param string $needle The substring to search for in the `$haystack`.
297+
* @return bool True if `$haystack` ends with `$needle`, otherwise false.
298+
*/
299+
function str_ends_with( $haystack, $needle ) {
300+
if ( '' === $haystack ) {
301+
return '' === $needle;
302+
}
303+
304+
$len = strlen( $needle );
305+
306+
return substr( $haystack, -$len, $len ) === $needle;
307+
}
308+
}

0 commit comments

Comments
 (0)