Make WordPress Core

Changeset 52040


Ignore:
Timestamp:
11/08/2021 02:21:44 PM (3 years ago)
Author:
hellofromTonya
Message:

General: Introduce polyfills for str_ends_with() and str_starts_with() added in PHP 8.0.

PHP 8.0 introduced two new functions: str_ends_with() and str_starts_with(). These perform a case-sensitive check indicating if the string to search in (haystack) ends or begins with the given substring (needle).

These polyfills make these functios available for use in Core.

Ref:

Props costdev, hellofromTonya, pbearne, pbiron.
Fixes #54377.

Location:
trunk
Files:
2 added
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/wp-includes/compat.php

    r52039 r52040  
    436436}
    437437
     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        return 0 === strpos( $haystack, $needle );
     456    }
     457}
     458
     459if ( ! function_exists( 'str_ends_with' ) ) {
     460    /**
     461     * Polyfill for `str_ends_with()` function added in PHP 8.0.
     462     *
     463     * Performs a case-sensitive check indicating if
     464     * the haystack ends with needle.
     465     *
     466     * @since 5.9.0
     467     *
     468     * @param string $haystack The string to search in.
     469     * @param string $needle   The substring to search for in the `$haystack`.
     470     * @return bool True if `$haystack` ends with `$needle`, otherwise false.
     471     */
     472    function str_ends_with( $haystack, $needle ) {
     473        if ( '' === $haystack && '' !== $needle ) {
     474            return false;
     475        }
     476        $len = strlen( $needle );
     477        return 0 === substr_compare( $haystack, $needle, -$len, $len );
     478    }
     479}
     480
    438481// IMAGETYPE_WEBP constant is only defined in PHP 7.1 or later.
    439482if ( ! defined( 'IMAGETYPE_WEBP' ) ) {
Note: See TracChangeset for help on using the changeset viewer.