Skip to content

Commit ff98b3b

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

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
@@ -434,3 +434,49 @@ public function jsonSerialize();
434434
if ( ! function_exists( 'random_int' ) ) {
435435
require ABSPATH . WPINC . '/random_compat/random.php';
436436
}
437+
438+
if ( ! function_exists( 'str_starts_with' ) ) {
439+
/**
440+
* Polyfill for `str_starts_with()` function added in PHP 8.0.
441+
*
442+
* Performs a case-sensitive check indicating if
443+
* the haystack begins with needle.
444+
*
445+
* @since 5.9.0
446+
*
447+
* @param string $haystack The string to search in.
448+
* @param string $needle The substring to search for in the `$haystack`.
449+
* @return bool True if `$haystack` starts with `$needle`, otherwise false.
450+
*/
451+
function str_starts_with( $haystack, $needle ) {
452+
if ( '' === $needle ) {
453+
return true;
454+
}
455+
456+
return 0 === strpos( $haystack, $needle );
457+
}
458+
}
459+
460+
if ( ! function_exists( 'str_ends_with' ) ) {
461+
/**
462+
* Polyfill for `str_ends_with()` function added in PHP 8.0.
463+
*
464+
* Performs a case-sensitive check indicating if
465+
* the haystack ends with needle.
466+
*
467+
* @since 5.9.0
468+
*
469+
* @param string $haystack The string to search in.
470+
* @param string $needle The substring to search for in the `$haystack`.
471+
* @return bool True if `$haystack` ends with `$needle`, otherwise false.
472+
*/
473+
function str_ends_with( $haystack, $needle ) {
474+
if ( '' === $haystack ) {
475+
return '' === $needle;
476+
}
477+
478+
$len = strlen( $needle );
479+
480+
return substr( $haystack, -$len, $len ) === $needle;
481+
}
482+
}

0 commit comments

Comments
 (0)