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.

git-svn-id: https://develop.svn.wordpress.org/trunk@55990 602fd350-edb4-49c9-b593-d223f7449a82
This commit is contained in:
Sergey Biryukov
2023-06-22 14:55:47 +00:00
parent 38950d24c3
commit 66674fbfd9
41 changed files with 82 additions and 82 deletions
+5 -5
View File
@@ -513,7 +513,7 @@ function human_readable_duration( $duration = '' ) {
$duration = trim( $duration );
// Remove prepended negative sign.
if ( '-' === substr( $duration, 0, 1 ) ) {
if ( str_starts_with( $duration, '-' ) ) {
$duration = substr( $duration, 1 );
}
@@ -743,7 +743,7 @@ function is_serialized_string( $data ) {
return false;
} elseif ( ':' !== $data[1] ) {
return false;
} elseif ( ';' !== substr( $data, -1 ) ) {
} elseif ( ! str_ends_with( $data, ';' ) ) {
return false;
} elseif ( 's' !== $data[0] ) {
return false;
@@ -6361,17 +6361,17 @@ function _wp_timezone_choice_usort_callback( $a, $b ) {
// Don't use translated versions of Etc.
if ( 'Etc' === $a['continent'] && 'Etc' === $b['continent'] ) {
// Make the order of these more like the old dropdown.
if ( 'GMT+' === substr( $a['city'], 0, 4 ) && 'GMT+' === substr( $b['city'], 0, 4 ) ) {
if ( str_starts_with( $a['city'], 'GMT+' ) && str_starts_with( $b['city'], 'GMT+' ) ) {
return -1 * ( strnatcasecmp( $a['city'], $b['city'] ) );
}
if ( 'UTC' === $a['city'] ) {
if ( 'GMT+' === substr( $b['city'], 0, 4 ) ) {
if ( str_starts_with( $b['city'], 'GMT+' ) ) {
return 1;
}
return -1;
}
if ( 'UTC' === $b['city'] ) {
if ( 'GMT+' === substr( $a['city'], 0, 4 ) ) {
if ( str_starts_with( $a['city'], 'GMT+' ) ) {
return -1;
}
return 1;