General: Backport polyfills for str_ends_with() and str_starts_with() .

Merges [52040], [56016], and [56015] to 5.8 branch.

Props ocean90, SergeyBiryukov, desrosj, joemcgill, jorbin, mukesh27.

Built from https://develop.svn.wordpress.org/branches/5.8@57449


git-svn-id: http://core.svn.wordpress.org/branches/5.8@56950 1a063a9b-81f0-0310-95a4-ce76da25c4cd
This commit is contained in:
Joe McGill 2024-01-30 17:50:01 +00:00
parent 65fa3acb4b
commit 913f7b642f
1 changed files with 46 additions and 0 deletions

View File

@ -371,6 +371,52 @@ if ( ! function_exists( 'is_iterable' ) ) {
}
}
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 ) {
return '' === $needle;
}
$len = strlen( $needle );
return substr( $haystack, -$len, $len ) === $needle;
}
}
// IMAGETYPE_WEBP constant is only defined in PHP 7.1 or later.
if ( ! defined( 'IMAGETYPE_WEBP' ) ) {
define( 'IMAGETYPE_WEBP', 18 );