Make WordPress Core

Changeset 57459


Ignore:
Timestamp:
01/30/2024 06:22:15 PM (8 months ago)
Author:
jorbin
Message:

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

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

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

Location:
branches/5.1
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • branches/5.1

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

    r43220 r57459  
    546546    }
    547547}
     548
     549if ( ! function_exists( 'str_starts_with' ) ) {
     550    /**
     551     * Polyfill for `str_starts_with()` function added in PHP 8.0.
     552     *
     553     * Performs a case-sensitive check indicating if
     554     * the haystack begins with needle.
     555     *
     556     * @since 5.9.0
     557     *
     558     * @param string $haystack The string to search in.
     559     * @param string $needle   The substring to search for in the `$haystack`.
     560     * @return bool True if `$haystack` starts with `$needle`, otherwise false.
     561     */
     562    function str_starts_with( $haystack, $needle ) {
     563        if ( '' === $needle ) {
     564            return true;
     565        }
     566
     567        return 0 === strpos( $haystack, $needle );
     568    }
     569}
     570
     571if ( ! function_exists( 'str_ends_with' ) ) {
     572    /**
     573     * Polyfill for `str_ends_with()` function added in PHP 8.0.
     574     *
     575     * Performs a case-sensitive check indicating if
     576     * the haystack ends with needle.
     577     *
     578     * @since 5.9.0
     579     *
     580     * @param string $haystack The string to search in.
     581     * @param string $needle   The substring to search for in the `$haystack`.
     582     * @return bool True if `$haystack` ends with `$needle`, otherwise false.
     583     */
     584    function str_ends_with( $haystack, $needle ) {
     585        if ( '' === $haystack ) {
     586            return '' === $needle;
     587        }
     588
     589        $len = strlen( $needle );
     590
     591        return substr( $haystack, -$len, $len ) === $needle;
     592    }
     593}
Note: See TracChangeset for help on using the changeset viewer.