From cbee32cff7b8e2f45e7d4c5f82fb2458ed99dfeb Mon Sep 17 00:00:00 2001 From: Aaron Jorbin Date: Tue, 30 Jan 2024 17:29:22 +0000 Subject: [PATCH] General: Backport polyfills for `str_ends_with()` and `str_starts_with()`. Merges [52040], [56016], and [56015] to 4.4 branch. Props ocean90, SergeyBiryukov, desrosj, joemcgill, jorbin, mukesh27. Built from https://develop.svn.wordpress.org/branches/4.4@57442 git-svn-id: http://core.svn.wordpress.org/branches/4.4@56948 1a063a9b-81f0-0310-95a4-ce76da25c4cd --- wp-includes/compat.php | 46 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/wp-includes/compat.php b/wp-includes/compat.php index 24da0adc3e..3ad2a53708 100644 --- a/wp-includes/compat.php +++ b/wp-includes/compat.php @@ -337,3 +337,49 @@ if ( ! interface_exists( 'JsonSerializable' ) ) { if ( ! function_exists( 'random_int' ) ) { require ABSPATH . WPINC . '/random_compat/random.php'; } + +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; + } +}