Make WordPress Core

Changeset 57440


Ignore:
Timestamp:
01/30/2024 05:25:24 PM (3 weeks ago)
Author:
jorbin
Message:

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.

Location:
branches/4.3
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • branches/4.3

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

    r32672 r57440  
    261261    define( 'JSON_PRETTY_PRINT', 128 );
    262262}
     263
     264if ( ! 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
     286if ( ! 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}
Note: See TracChangeset for help on using the changeset viewer.