Skip to content

Commit 7bd333d

Browse files
committed
General: Backport polyfills for str_ends_with() and str_starts_with() .
Merges [52040], [56016], and [56015] to 4.1 branch. Props ocean90, SergeyBiryukov, desrosj, joemcgill, jorbin, mukesh27. git-svn-id: https://develop.svn.wordpress.org/branches/4.1@57438 602fd350-edb4-49c9-b593-d223f7449a82
1 parent 6e49b5d commit 7bd333d

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

src/wp-includes/compat.php

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -247,3 +247,49 @@ function hash_equals( $a, $b ) {
247247
if ( ! defined( 'JSON_PRETTY_PRINT' ) ) {
248248
define( 'JSON_PRETTY_PRINT', 128 );
249249
}
250+
251+
if ( ! function_exists( 'str_starts_with' ) ) {
252+
/**
253+
* Polyfill for `str_starts_with()` function added in PHP 8.0.
254+
*
255+
* Performs a case-sensitive check indicating if
256+
* the haystack begins with needle.
257+
*
258+
* @since 5.9.0
259+
*
260+
* @param string $haystack The string to search in.
261+
* @param string $needle The substring to search for in the `$haystack`.
262+
* @return bool True if `$haystack` starts with `$needle`, otherwise false.
263+
*/
264+
function str_starts_with( $haystack, $needle ) {
265+
if ( '' === $needle ) {
266+
return true;
267+
}
268+
269+
return 0 === strpos( $haystack, $needle );
270+
}
271+
}
272+
273+
if ( ! function_exists( 'str_ends_with' ) ) {
274+
/**
275+
* Polyfill for `str_ends_with()` function added in PHP 8.0.
276+
*
277+
* Performs a case-sensitive check indicating if
278+
* the haystack ends with needle.
279+
*
280+
* @since 5.9.0
281+
*
282+
* @param string $haystack The string to search in.
283+
* @param string $needle The substring to search for in the `$haystack`.
284+
* @return bool True if `$haystack` ends with `$needle`, otherwise false.
285+
*/
286+
function str_ends_with( $haystack, $needle ) {
287+
if ( '' === $haystack ) {
288+
return '' === $needle;
289+
}
290+
291+
$len = strlen( $needle );
292+
293+
return substr( $haystack, -$len, $len ) === $needle;
294+
}
295+
}

0 commit comments

Comments
 (0)