Make WordPress Core

Changeset 57460 for branches/5.4


Ignore:
Timestamp:
01/30/2024 06:27:04 PM (8 months ago)
Author:
joemcgill
Message:

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

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

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

Location:
branches/5.4
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • branches/5.4

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

    r47219 r57460  
    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.