Make WordPress Core

Changeset 57451


Ignore:
Timestamp:
01/30/2024 06:02:05 PM (11 months ago)
Author:
joemcgill
Message:

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

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

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

Location:
branches/5.7
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • branches/5.7

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

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