From 517ea4aa3cc81afdc44f1023f1d231f08464bee3 Mon Sep 17 00:00:00 2001 From: Joe McGill Date: Tue, 30 Jan 2024 18:27:04 +0000 Subject: [PATCH] General: Backport polyfills for str_ends_with() and str_starts_with() . Merges [52040], [56016], and [56015] to 5.4 branch. Props ocean90, SergeyBiryukov, desrosj, joemcgill, jorbin, mukesh27. git-svn-id: https://develop.svn.wordpress.org/branches/5.4@57460 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/compat.php | 46 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/src/wp-includes/compat.php b/src/wp-includes/compat.php index 2e258a88ea..0d17dedfba 100644 --- a/src/wp-includes/compat.php +++ b/src/wp-includes/compat.php @@ -374,3 +374,49 @@ if ( ! function_exists( 'is_iterable' ) ) { return ( is_array( $var ) || $var instanceof Traversable ); } } + +if ( ! function_exists( 'str_starts_with' ) ) { + /** + * Polyfill for `str_starts_with()` function added in PHP 8.0. + * + * Performs a case-sensitive check indicating if + * the haystack begins with needle. + * + * @since 5.9.0 + * + * @param string $haystack The string to search in. + * @param string $needle The substring to search for in the `$haystack`. + * @return bool True if `$haystack` starts with `$needle`, otherwise false. + */ + function str_starts_with( $haystack, $needle ) { + if ( '' === $needle ) { + return true; + } + + return 0 === strpos( $haystack, $needle ); + } +} + +if ( ! function_exists( 'str_ends_with' ) ) { + /** + * Polyfill for `str_ends_with()` function added in PHP 8.0. + * + * Performs a case-sensitive check indicating if + * the haystack ends with needle. + * + * @since 5.9.0 + * + * @param string $haystack The string to search in. + * @param string $needle The substring to search for in the `$haystack`. + * @return bool True if `$haystack` ends with `$needle`, otherwise false. + */ + function str_ends_with( $haystack, $needle ) { + if ( '' === $haystack ) { + return '' === $needle; + } + + $len = strlen( $needle ); + + return substr( $haystack, -$len, $len ) === $needle; + } +}