Make WordPress Core


Ignore:
Timestamp:
06/22/2023 02:55:47 PM (18 months ago)
Author:
SergeyBiryukov
Message:

Code Modernization: Replace usage of substr() with str_starts_with() and str_ends_with().

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

WordPress core includes a polyfill for these functions on PHP < 8.0 as of WordPress 5.9.

This commit uses str_starts_with() and str_ends_with() in core files where appropriate:

  • $needle === substr( $string, 0, $length ), where $length is the length of $needle, is replaced with str_starts_with( $haystack, $needle ).
  • $needle === substr( $string, $offset ), where $offset is negative and the absolute value of $offset is the length of $needle, is replaced with str_ends_with( $haystack, $needle ).

This aims to make the code more readable and consistent, as well as better aligned with modern development practices.

Follow-up to [52039], [52040], [52326], [55703], [55710], [55987], [55988].

Props Soean, spacedmonkey, Clorith, ocean90, azaozz, sabernhardt, SergeyBiryukov.
Fixes #58220.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/wp-includes/class-wp-http-cookie.php

    r55827 r55990  
    116116        }
    117117        $this->path = isset( $parsed_url['path'] ) ? $parsed_url['path'] : '/';
    118         if ( '/' !== substr( $this->path, -1 ) ) {
     118        if ( ! str_ends_with( $this->path, '/' ) ) {
    119119            $this->path = dirname( $this->path ) . '/';
    120120        }
     
    203203
    204204        // Host - very basic check that the request URL ends with the domain restriction (minus leading dot).
    205         $domain = ( '.' === substr( $domain, 0, 1 ) ) ? substr( $domain, 1 ) : $domain;
     205        $domain = ( str_starts_with( $domain, '.' ) ) ? substr( $domain, 1 ) : $domain;
    206206        if ( substr( $url['host'], -strlen( $domain ) ) !== $domain ) {
    207207            return false;
Note: See TracChangeset for help on using the changeset viewer.