Make WordPress Core

Changeset 57443


Ignore:
Timestamp:
01/30/2024 05:29:21 PM (3 years ago)
Author:
jorbin
Message:

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

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

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

Location:
branches/4.5
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • branches/4.5

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

    r36490 r57443  
    435435        require ABSPATH . WPINC . '/random_compat/random.php';
    436436}
     437
     438if ( ! function_exists( 'str_starts_with' ) ) {
     439        /**
     440         * Polyfill for `str_starts_with()` function added in PHP 8.0.
     441         *
     442         * Performs a case-sensitive check indicating if
     443         * the haystack begins with needle.
     444         *
     445         * @since 5.9.0
     446         *
     447         * @param string $haystack The string to search in.
     448         * @param string $needle   The substring to search for in the `$haystack`.
     449         * @return bool True if `$haystack` starts with `$needle`, otherwise false.
     450         */
     451        function str_starts_with( $haystack, $needle ) {
     452                if ( '' === $needle ) {
     453                        return true;
     454                }
     455
     456                return 0 === strpos( $haystack, $needle );
     457        }
     458}
     459
     460if ( ! function_exists( 'str_ends_with' ) ) {
     461        /**
     462         * Polyfill for `str_ends_with()` function added in PHP 8.0.
     463         *
     464         * Performs a case-sensitive check indicating if
     465         * the haystack ends with needle.
     466         *
     467         * @since 5.9.0
     468         *
     469         * @param string $haystack The string to search in.
     470         * @param string $needle   The substring to search for in the `$haystack`.
     471         * @return bool True if `$haystack` ends with `$needle`, otherwise false.
     472         */
     473        function str_ends_with( $haystack, $needle ) {
     474                if ( '' === $haystack ) {
     475                        return '' === $needle;
     476                }
     477
     478                $len = strlen( $needle );
     479
     480                return substr( $haystack, -$len, $len ) === $needle;
     481        }
     482}
Note: See TracChangeset for help on using the changeset viewer.