Make WordPress Core


Ignore:
Timestamp:
06/22/2023 02:55:47 PM (11 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/class-wp-screen.php

    r55984 r55990  
    231231            $id        = 'post'; // Changes later. Ends up being $base.
    232232        } else {
    233             if ( '.php' === substr( $id, -4 ) ) {
     233            if ( str_ends_with( $id, '.php' ) ) {
    234234                $id = substr( $id, 0, -4 );
    235235            }
     
    242242
    243243        if ( ! $post_type && $hook_name ) {
    244             if ( '-network' === substr( $id, -8 ) ) {
     244            if ( str_ends_with( $id, '-network' ) ) {
    245245                $id       = substr( $id, 0, -8 );
    246246                $in_admin = 'network';
    247             } elseif ( '-user' === substr( $id, -5 ) ) {
     247            } elseif ( str_ends_with( $id, '-user' ) ) {
    248248                $id       = substr( $id, 0, -5 );
    249249                $in_admin = 'user';
     
    251251
    252252            $id = sanitize_key( $id );
    253             if ( 'edit-comments' !== $id && 'edit-tags' !== $id && 'edit-' === substr( $id, 0, 5 ) ) {
     253            if ( 'edit-comments' !== $id && 'edit-tags' !== $id && str_starts_with( $id, 'edit-' ) ) {
    254254                $maybe = substr( $id, 5 );
    255255                if ( taxonomy_exists( $maybe ) ) {
Note: See TracChangeset for help on using the changeset viewer.