Skip to content

Commit

Permalink
General: Backport polyfills for str_ends_with() and `str_starts_wit…
Browse files Browse the repository at this point in the history
…h()`.

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

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


git-svn-id: https://develop.svn.wordpress.org/branches/5.1@57459 602fd350-edb4-49c9-b593-d223f7449a82
  • Loading branch information
aaronjorbin committed Jan 30, 2024
1 parent 5e018ba commit 83c416b
Showing 1 changed file with 46 additions and 0 deletions.
46 changes: 46 additions & 0 deletions src/wp-includes/compat.php
Original file line number Diff line number Diff line change
Expand Up @@ -545,3 +545,49 @@ function is_iterable( $var ) {
return ( is_array( $var ) || $var instanceof Traversable );
}
}

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;
}
}

0 comments on commit 83c416b

Please sign in to comment.