Skip to content

Commit a796777

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

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
@@ -374,3 +374,49 @@ function is_iterable( $var ) {
374374
return ( is_array( $var ) || $var instanceof Traversable );
375375
}
376376
}
377+
378+
if ( ! function_exists( 'str_starts_with' ) ) {
379+
/**
380+
* Polyfill for `str_starts_with()` function added in PHP 8.0.
381+
*
382+
* Performs a case-sensitive check indicating if
383+
* the haystack begins with needle.
384+
*
385+
* @since 5.9.0
386+
*
387+
* @param string $haystack The string to search in.
388+
* @param string $needle The substring to search for in the `$haystack`.
389+
* @return bool True if `$haystack` starts with `$needle`, otherwise false.
390+
*/
391+
function str_starts_with( $haystack, $needle ) {
392+
if ( '' === $needle ) {
393+
return true;
394+
}
395+
396+
return 0 === strpos( $haystack, $needle );
397+
}
398+
}
399+
400+
if ( ! function_exists( 'str_ends_with' ) ) {
401+
/**
402+
* Polyfill for `str_ends_with()` function added in PHP 8.0.
403+
*
404+
* Performs a case-sensitive check indicating if
405+
* the haystack ends with needle.
406+
*
407+
* @since 5.9.0
408+
*
409+
* @param string $haystack The string to search in.
410+
* @param string $needle The substring to search for in the `$haystack`.
411+
* @return bool True if `$haystack` ends with `$needle`, otherwise false.
412+
*/
413+
function str_ends_with( $haystack, $needle ) {
414+
if ( '' === $haystack ) {
415+
return '' === $needle;
416+
}
417+
418+
$len = strlen( $needle );
419+
420+
return substr( $haystack, -$len, $len ) === $needle;
421+
}
422+
}

0 commit comments

Comments
 (0)