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/media.php

    r55988 r55990  
    13551355    $post = get_post( $attachment_id );
    13561356
    1357     if ( 'image' === substr( $post->post_mime_type, 0, 5 ) ) {
     1357    if ( str_starts_with( $post->post_mime_type, 'image' ) ) {
    13581358        $url   = $attachment['url'];
    13591359        $align = ! empty( $attachment['align'] ) ? $attachment['align'] : 'none';
     
    14661466
    14671467    // This was formerly in image_attachment_fields_to_edit().
    1468     if ( 'image' === substr( $post->post_mime_type, 0, 5 ) ) {
     1468    if ( str_starts_with( $post->post_mime_type, 'image' ) ) {
    14691469        $alt = get_post_meta( $post->ID, '_wp_attachment_image_alt', true );
    14701470
     
    32213221    </div>
    32223222    <div class="wp_attachment_details edit-form-section">
    3223     <?php if ( 'image' === substr( $post->post_mime_type, 0, 5 ) ) : ?>
     3223    <?php if ( str_starts_with( $post->post_mime_type, 'image' ) ) : ?>
    32243224        <p class="attachment-alt-text">
    32253225            <label for="attachment_alt"><strong><?php _e( 'Alternative Text' ); ?></strong></label><br />
Note: See TracChangeset for help on using the changeset viewer.