General: Introduce polyfills for `str_ends_with()` and `str_starts_with()` added in PHP 8.0.

PHP 8.0 introduced two new functions: `str_ends_with()` and `str_starts_with()`. These perform a case-sensitive check indicating if the string to search in (haystack) ends or begins with the given substring (needle).

These polyfills make these functios available for use in Core.

Ref:
* PHP RFC https://wiki.php.net/rfc/add_str_starts_with_and_ends_with_functions
* PHP manual `str_ends_with()` https://www.php.net/manual/en/function.str-ends-with.php
* PHP manual `str_starts_with()`  https://www.php.net/manual/en/function.str-starts-with.php

Props costdev, hellofromTonya, pbearne, pbiron.
Fixes #54377.
Built from https://develop.svn.wordpress.org/trunk@52040


git-svn-id: http://core.svn.wordpress.org/trunk@51632 1a063a9b-81f0-0310-95a4-ce76da25c4cd
This commit is contained in:
hellofromTonya 2021-11-08 14:22:57 +00:00
parent 87557c6260
commit 3d10105120
2 changed files with 44 additions and 1 deletions

View File

@ -435,6 +435,49 @@ if ( ! function_exists( 'str_contains' ) ) {
}
}
if ( ! function_exists( 'str_starts_with' ) ) {
/**
* Polyfill for `str_starts_with()` function added in PHP 8.0.
*
* Performs a case-sensitive check indicating if
* the haystack begins with needle.
*
* @since 5.9.0
*
* @param string $haystack The string to search in.
* @param string $needle The substring to search for in the `$haystack`.
* @return bool True if `$haystack` starts with `$needle`, otherwise false.
*/
function str_starts_with( $haystack, $needle ) {
if ( '' === $needle ) {
return true;
}
return 0 === strpos( $haystack, $needle );
}
}
if ( ! function_exists( 'str_ends_with' ) ) {
/**
* Polyfill for `str_ends_with()` function added in PHP 8.0.
*
* Performs a case-sensitive check indicating if
* the haystack ends with needle.
*
* @since 5.9.0
*
* @param string $haystack The string to search in.
* @param string $needle The substring to search for in the `$haystack`.
* @return bool True if `$haystack` ends with `$needle`, otherwise false.
*/
function str_ends_with( $haystack, $needle ) {
if ( '' === $haystack && '' !== $needle ) {
return false;
}
$len = strlen( $needle );
return 0 === substr_compare( $haystack, $needle, -$len, $len );
}
}
// IMAGETYPE_WEBP constant is only defined in PHP 7.1 or later.
if ( ! defined( 'IMAGETYPE_WEBP' ) ) {
define( 'IMAGETYPE_WEBP', 18 );

View File

@ -16,7 +16,7 @@
*
* @global string $wp_version
*/
$wp_version = '5.9-alpha-52039';
$wp_version = '5.9-alpha-52040';
/**
* Holds the WordPress DB revision, increments when changes are made to the WordPress DB schema.