Skip to content

Commit 76ef279

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

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
@@ -537,3 +537,49 @@ function is_iterable( $var ) {
537537
return ( is_array( $var ) || $var instanceof Traversable );
538538
}
539539
}
540+
541+
if ( ! function_exists( 'str_starts_with' ) ) {
542+
/**
543+
* Polyfill for `str_starts_with()` function added in PHP 8.0.
544+
*
545+
* Performs a case-sensitive check indicating if
546+
* the haystack begins with needle.
547+
*
548+
* @since 5.9.0
549+
*
550+
* @param string $haystack The string to search in.
551+
* @param string $needle The substring to search for in the `$haystack`.
552+
* @return bool True if `$haystack` starts with `$needle`, otherwise false.
553+
*/
554+
function str_starts_with( $haystack, $needle ) {
555+
if ( '' === $needle ) {
556+
return true;
557+
}
558+
559+
return 0 === strpos( $haystack, $needle );
560+
}
561+
}
562+
563+
if ( ! function_exists( 'str_ends_with' ) ) {
564+
/**
565+
* Polyfill for `str_ends_with()` function added in PHP 8.0.
566+
*
567+
* Performs a case-sensitive check indicating if
568+
* the haystack ends with needle.
569+
*
570+
* @since 5.9.0
571+
*
572+
* @param string $haystack The string to search in.
573+
* @param string $needle The substring to search for in the `$haystack`.
574+
* @return bool True if `$haystack` ends with `$needle`, otherwise false.
575+
*/
576+
function str_ends_with( $haystack, $needle ) {
577+
if ( '' === $haystack ) {
578+
return '' === $needle;
579+
}
580+
581+
$len = strlen( $needle );
582+
583+
return substr( $haystack, -$len, $len ) === $needle;
584+
}
585+
}

0 commit comments

Comments
 (0)