Make WordPress Core


Ignore:
Timestamp:
05/02/2023 03:43:03 PM (17 months ago)
Author:
SergeyBiryukov
Message:

Code Modernization: Replace usage of strpos() with str_starts_with().

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

WordPress core includes a polyfill for str_starts_with() on PHP < 8.0 as of WordPress 5.9.

This commit replaces 0 === strpos( ... ) with str_starts_with() in core files, making the code more readable and consistent, as well as improving performance.

While strpos() is slightly faster than the polyfill on PHP < 8.0, str_starts_with() is noticeably faster on PHP 8.0+, as it is optimized to avoid unnecessarily searching along the whole haystack if it does not find the needle.

Follow-up to [52039], [52040], [52326].

Props spacedmonkey, costdev, sabernhardt, mukesh27, desrosj, jorbin, TobiasBg, ayeshrajans, lgadzhev, SergeyBiryukov.
Fixes #58012.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/wp-includes/post.php

    r55702 r55703  
    724724
    725725    // If the file is relative, prepend upload dir.
    726     if ( $file && 0 !== strpos( $file, '/' ) && ! preg_match( '|^.:\\\|', $file ) ) {
     726    if ( $file && ! str_starts_with( $file, '/' ) && ! preg_match( '|^.:\\\|', $file ) ) {
    727727        $uploads = wp_get_upload_dir();
    728728        if ( false === $uploads['error'] ) {
     
    796796
    797797    $uploads = wp_get_upload_dir();
    798     if ( 0 === strpos( $new_path, $uploads['basedir'] ) ) {
     798    if ( str_starts_with( $new_path, $uploads['basedir'] ) ) {
    799799            $new_path = str_replace( $uploads['basedir'], '', $new_path );
    800800            $new_path = ltrim( $new_path, '/' );
     
    64846484        if ( $uploads && false === $uploads['error'] ) {
    64856485            // Check that the upload base exists in the file location.
    6486             if ( 0 === strpos( $file, $uploads['basedir'] ) ) {
     6486            if ( str_starts_with( $file, $uploads['basedir'] ) ) {
    64876487                // Replace file location with url location.
    64886488                $url = str_replace( $uploads['basedir'], $uploads['baseurl'], $file );
     
    66136613    }
    66146614
    6615     if ( 0 === strpos( $post->post_mime_type, $type . '/' ) ) {
     6615    if ( str_starts_with( $post->post_mime_type, $type . '/' ) ) {
    66166616        return true;
    66176617    }
Note: See TracChangeset for help on using the changeset viewer.