Make WordPress Core

Changeset 57439


Ignore:
Timestamp:
01/30/2024 05:20:42 PM (10 months ago)
Author:
jorbin
Message:

General: Backport polyfills for str_ends_with() and str_starts_with().

Merges [52040], [56016], and [56015] to 4.2 branch.

Props ocean90, SergeyBiryukov, desrosj, joemcgill, jorbin, mukesh27.

Location:
branches/4.2
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • branches/4.2

  • branches/4.2/src/wp-includes/compat.php

    r32367 r57439  
    248248    define( 'JSON_PRETTY_PRINT', 128 );
    249249}
     250
     251if ( ! function_exists( 'str_starts_with' ) ) {
     252    /**
     253     * Polyfill for `str_starts_with()` function added in PHP 8.0.
     254     *
     255     * Performs a case-sensitive check indicating if
     256     * the haystack begins with needle.
     257     *
     258     * @since 5.9.0
     259     *
     260     * @param string $haystack The string to search in.
     261     * @param string $needle   The substring to search for in the `$haystack`.
     262     * @return bool True if `$haystack` starts with `$needle`, otherwise false.
     263     */
     264    function str_starts_with( $haystack, $needle ) {
     265        if ( '' === $needle ) {
     266            return true;
     267        }
     268
     269        return 0 === strpos( $haystack, $needle );
     270    }
     271}
     272
     273if ( ! function_exists( 'str_ends_with' ) ) {
     274    /**
     275     * Polyfill for `str_ends_with()` function added in PHP 8.0.
     276     *
     277     * Performs a case-sensitive check indicating if
     278     * the haystack ends with needle.
     279     *
     280     * @since 5.9.0
     281     *
     282     * @param string $haystack The string to search in.
     283     * @param string $needle   The substring to search for in the `$haystack`.
     284     * @return bool True if `$haystack` ends with `$needle`, otherwise false.
     285     */
     286    function str_ends_with( $haystack, $needle ) {
     287        if ( '' === $haystack ) {
     288            return '' === $needle;
     289        }
     290
     291        $len = strlen( $needle );
     292
     293        return substr( $haystack, -$len, $len ) === $needle;
     294    }
     295}
Note: See TracChangeset for help on using the changeset viewer.