Make WordPress Core

Changeset 57461


Ignore:
Timestamp:
01/30/2024 06:28:01 PM (3 weeks ago)
Author:
jorbin
Message:

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

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

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

Location:
branches/5.2
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • branches/5.2

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

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