Make WordPress Core


Ignore:
Timestamp:
01/30/2024 06:28:59 PM (3 years ago)
Author:
joemcgill
Message:

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

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

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

Location:
branches/5.3
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • branches/5.3

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

    r46208 r57462  
    375375        }
    376376}
     377
     378if ( ! function_exists( 'str_starts_with' ) ) {
     379        /**
     380         * Polyfill for `str_starts_with()` function added in PHP 8.0.
     381         *
     382         * Performs a case-sensitive check indicating if
     383         * the haystack begins with needle.
     384         *
     385         * @since 5.9.0
     386         *
     387         * @param string $haystack The string to search in.
     388         * @param string $needle   The substring to search for in the `$haystack`.
     389         * @return bool True if `$haystack` starts with `$needle`, otherwise false.
     390         */
     391        function str_starts_with( $haystack, $needle ) {
     392                if ( '' === $needle ) {
     393                        return true;
     394                }
     395
     396                return 0 === strpos( $haystack, $needle );
     397        }
     398}
     399
     400if ( ! function_exists( 'str_ends_with' ) ) {
     401        /**
     402         * Polyfill for `str_ends_with()` function added in PHP 8.0.
     403         *
     404         * Performs a case-sensitive check indicating if
     405         * the haystack ends with needle.
     406         *
     407         * @since 5.9.0
     408         *
     409         * @param string $haystack The string to search in.
     410         * @param string $needle   The substring to search for in the `$haystack`.
     411         * @return bool True if `$haystack` ends with `$needle`, otherwise false.
     412         */
     413        function str_ends_with( $haystack, $needle ) {
     414                if ( '' === $haystack ) {
     415                        return '' === $needle;
     416                }
     417
     418                $len = strlen( $needle );
     419
     420                return substr( $haystack, -$len, $len ) === $needle;
     421        }
     422}
Note: See TracChangeset for help on using the changeset viewer.