Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Code modernization: Replace usage of strpos with str_starts_with #32854

Closed
Tracked by #32865
jeherve opened this issue Sep 5, 2023 · 1 comment · Fixed by #34135
Closed
Tracked by #32865

Code modernization: Replace usage of strpos with str_starts_with #32854

jeherve opened this issue Sep 5, 2023 · 1 comment · Fixed by #34135

Comments

@jeherve
Copy link
Member

jeherve commented Sep 5, 2023

Source: https://core.trac.wordpress.org/ticket/58012

Let's follow Core's lead once Jetpack requires WordPress 6.3.

Primary issue: #32865

@jeherve jeherve changed the title Code modernization: Replace usage of strpos with str_starts_with https://core.trac.wordpress.org/ticket/58012 Code modernization: Replace usage of strpos with str_starts_with Sep 5, 2023
@anomiex
Copy link
Contributor

anomiex commented Sep 5, 2023

Note we can only do that in contexts that run under WordPress. Code that is intended to be useful outside of WordPress won't have WordPress's polyfill.

@jeherve jeherve self-assigned this Nov 13, 2023
jeherve added a commit that referenced this issue Nov 15, 2023
Fixes #32854

str_starts_with() was introduced in PHP 8.0 to perform a case-sensitive check indicating if the string to search in (haystack) begins with the given substring (needle).

WordPress core includes a polyfill for str_starts_with() on PHP < 8.0 as of WordPress 5.9.

This commit replaces usage of strpos() with str_starts_with(), making the code more readable and consistent, as well as improving performance in PHP 8+ environments.

While strpos() is slightly faster than the polyfill on PHP < 8.0, str_starts_with() is noticeably faster on PHP 8.0+, as it is optimized to avoid unnecessarily searching along the whole haystack if it does not find the needle.

Note: this doesn't update uses of strpos() in a few places:
- The autoloader since it can be used outside of WordPress.
- The VaultPress plugin since it can still be used on older versions of WordPress, where the str_starts_with() shim did not exist.

Matching core change: https://core.trac.wordpress.org/ticket/58012
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants