Make WordPress Core


Ignore:
Timestamp:
06/22/2023 02:55:47 PM (13 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/functions.php

    r55988 r55990  
    514514
    515515    // Remove prepended negative sign.
    516     if ( '-' === substr( $duration, 0, 1 ) ) {
     516    if ( str_starts_with( $duration, '-' ) ) {
    517517        $duration = substr( $duration, 1 );
    518518    }
     
    744744    } elseif ( ':' !== $data[1] ) {
    745745        return false;
    746     } elseif ( ';' !== substr( $data, -1 ) ) {
     746    } elseif ( ! str_ends_with( $data, ';' ) ) {
    747747        return false;
    748748    } elseif ( 's' !== $data[0] ) {
     
    63626362    if ( 'Etc' === $a['continent'] && 'Etc' === $b['continent'] ) {
    63636363        // Make the order of these more like the old dropdown.
    6364         if ( 'GMT+' === substr( $a['city'], 0, 4 ) && 'GMT+' === substr( $b['city'], 0, 4 ) ) {
     6364        if ( str_starts_with( $a['city'], 'GMT+' ) && str_starts_with( $b['city'], 'GMT+' ) ) {
    63656365            return -1 * ( strnatcasecmp( $a['city'], $b['city'] ) );
    63666366        }
    63676367        if ( 'UTC' === $a['city'] ) {
    6368             if ( 'GMT+' === substr( $b['city'], 0, 4 ) ) {
     6368            if ( str_starts_with( $b['city'], 'GMT+' ) ) {
    63696369                return 1;
    63706370            }
     
    63726372        }
    63736373        if ( 'UTC' === $b['city'] ) {
    6374             if ( 'GMT+' === substr( $a['city'], 0, 4 ) ) {
     6374            if ( str_starts_with( $a['city'], 'GMT+' ) ) {
    63756375                return -1;
    63766376            }
Note: See TracChangeset for help on using the changeset viewer.