Make WordPress Core


Ignore:
Timestamp:
06/22/2023 02:55:47 PM (5 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-admin/includes/plugin.php

    r55988 r55990  
    295295    if ( $plugins_dir ) {
    296296        while ( ( $file = readdir( $plugins_dir ) ) !== false ) {
    297             if ( '.' === substr( $file, 0, 1 ) ) {
     297            if ( str_starts_with( $file, '.' ) ) {
    298298                continue;
    299299            }
     
    304304                if ( $plugins_subdir ) {
    305305                    while ( ( $subfile = readdir( $plugins_subdir ) ) !== false ) {
    306                         if ( '.' === substr( $subfile, 0, 1 ) ) {
     306                        if ( str_starts_with( $subfile, '.' ) ) {
    307307                            continue;
    308308                        }
    309309
    310                         if ( '.php' === substr( $subfile, -4 ) ) {
     310                        if ( str_ends_with( $subfile, '.php' ) ) {
    311311                            $plugin_files[] = "$file/$subfile";
    312312                        }
     
    316316                }
    317317            } else {
    318                 if ( '.php' === substr( $file, -4 ) ) {
     318                if ( str_ends_with( $file, '.php' ) ) {
    319319                    $plugin_files[] = $file;
    320320                }
     
    372372    if ( $plugins_dir ) {
    373373        while ( ( $file = readdir( $plugins_dir ) ) !== false ) {
    374             if ( '.php' === substr( $file, -4 ) ) {
     374            if ( str_ends_with( $file, '.php' ) ) {
    375375                $plugin_files[] = $file;
    376376            }
Note: See TracChangeset for help on using the changeset viewer.