str_ends_with( string $haystack, string $needle ): bool
- Since
- 5.9.0
- Source
wp-includes/compat.php:543
Checks whether a haystack string ends with a given needle, matching case exactly. WordPress only defines this function when the site's PHP version doesn't already provide it natively (PHP 8.0+), so it behaves as a drop-in for the built-in str_ends_with(). Pair it with str_starts_with() or str_contains() when you need to test the other end or the middle of a string.
str_ends_with() function added in PHP 8.0.Description
Performs a case-sensitive check indicating if the haystack ends with needle.
Compatibility
- WordPress
- since 5.9.0
- PHP
- 7.4–8.6-dev
- 6.7.7
- 6.8.8
- 6.9.7
- 7.0.4
- 7.1.0
Present in every tracked release (6.7.7 to 7.1.0), and compiles on PHP 7.4 through 8.6-dev.
Parameters
$haystackstring- The string to search in.
$needlestring- The substring to search for in the
$haystack.
Return value
bool- True if
$haystackends with$needle, otherwise false.
Code examples
Every example is editable and runs in a real WordPress booted in your browser by WordPress Playground. Press Run, then edit the code: clicking away re-runs it. Nothing is sent anywhere until you do.
Check if a post permalink ends with its slug
Confirm that the permalink for the first sample post ends with the expected slug before building custom rewrite logic around it.
$permalink = get_permalink( 1 );
if ( str_ends_with( $permalink, 'hello-world' ) ) {
echo esc_html( 'Permalink ends with hello-world: ' . $permalink );
} else {
echo esc_html( 'Permalink does not end with hello-world: ' . $permalink );
}Reject uploaded file names with a disallowed extension
Loop over a small batch of candidate file names and keep only the ones ending in an approved image extension.
$filenames = array( 'holiday-photo.jpg', 'notes.txt', 'banner.PNG', 'archive.zip' );
$allowed = array( '.jpg', '.jpeg', '.png', '.gif' );
foreach ( $filenames as $filename ) {
$is_allowed = false;
foreach ( $allowed as $extension ) {
if ( str_ends_with( strtolower( $filename ), $extension ) ) {
$is_allowed = true;
break;
}
}
printf( '%s: %s<br>', esc_html( $filename ), $is_allowed ? 'allowed' : 'rejected' );
}Lowercase the file name first since str_ends_with() itself is case-sensitive.
Common problems and fixes · 3
- Why does str_ends_with() return true when I pass in two empty strings?
- Why doesn't str_ends_with() match when the casing is different?
- Why do I get a fatal error about str_ends_with() already being declared?
Why does str_ends_with() return true when I pass in two empty strings?
Why doesn't str_ends_with() match when the casing is different?
Why do I get a fatal error about str_ends_with() already being declared?
Alternatives and related functions
str_starts_with- When you need to check the beginning of a string instead of the end.
str_contains- When the substring can appear anywhere in the string, not just at the very end.
substr_compare- When you want the native PHP function directly and don't need WordPress's version-detection polyfill logic.
Performance profile
How much work a call to str_ends_with() does, and what it touches: the algorithmic scaling, the Zend instruction count per call across PHP versions, the hooks it hands control to, and the core code that calls it. Measured from the compiled opcodes, not a stopwatch, so every number is identical on any machine running the same PHP version, and every function in core is ranked by cost.
- Cost class
- Trivial
- Scaling
- Constant
- Instructions
- 6–10
- Plugin surface
- None
- Called by
- 49
Touches nothing outside its own arguments.
No loop in the body: the same number of instructions runs whatever you pass in.
Executed per call on PHP 8.5, depending on the branch taken. The body compiles to 12.
Nothing here hands control to plugin code.
49 places in core call this, so the cost is paid more often than your own code shows.
What one call costs · 1 distinct outcome
One number would be a lie: the work depends on which branch runs. These are every distinct cost str_ends_with() can have, taken from its control-flow graph on PHP 8.5.
| When | Instructions | Calls it makes |
|---|---|---|
| always | 6–10 | none |
Across PHP versions
| PHP | Compiled | Executed | Branches | Notes |
|---|---|---|---|---|
| 8.6-dev | 12 | 6–10 | 1 | |
| 8.5 | 12 | 6–10 | 1 | |
| 8.4 | 12 | 6–10 | 1 | 3 fewer instructions than PHP 8.3 |
| 8.3 | 15 | 6–13 | 1 | |
| 8.2 | 15 | 6–13 | 1 | |
| 8.1 | 15 | 6–13 | 1 | |
| 7.4 | 15 | 6–13 | 1 |
An instruction is not a fixed amount of time, so a matching count is not necessarily the same speed; what it rules out is a difference in the work itself.
Used by · 49
- Language_Pack_Upgrader::check_package()Checks that the package source contains .mo and .po files.
- PO::trim_quotes()
- WP_AI_Client_Event_Dispatcher::get_hook_name_portion_for_event()Converts an event object class name to a WordPress action hook name portion.
- WP_Block_Metadata_Registry::default_identifier_callback()Default identifier function to determine the block identifier from a given path.
- WP_Block_Patterns_Registry::get_content()Retrieves the content of a registered block pattern.
- WP_Block_Processor::next_token()Advance to the next block delimiter or HTML span in a document, indicating if one was found.
- WP_Customize_Manager::_validate_header_video()Callback for validating the header_video value.
- WP_Http_Cookie::__construct()Sets up this cookie object.
- WP_Http_Cookie::test()Confirms that it's OK to send this cookie to the URL checked against.
- WP_Icons_Registry::get_content()Retrieves the content of a registered icon.
- WP_Interactivity_API::data_wp_each_processor()Processes the `data-wp-each` directive.
- WP_REST_Attachments_Controller::get_filename_from_disposition()Parses filename from a Content-Disposition header value.
Show all 49
- WP_Rewrite::init()Sets up the object's properties.
- WP_Screen::get()Fetches a screen object.
- WP_Theme_JSON::update_button_width_declarations()Updates button width declarations to use a calc() formula for percentage values.
- _load_script_textdomain_from_src()Resolves and loads the translation JSON file for a given script or script module source URL.
- _unzip_file_ziparchive()Attempts to unzip an archive using the ZipArchive class.
- _wp_kses_allow_pdf_objects()Helper function to check if this is a safe PDF URL.
- download_url()Downloads a URL to a local temporary file using the WordPress HTTP API.
- force_balance_tags()Balances tags of string using a modified stack.
- generate_block_asset_handle()Generates the name for an asset based on the name of the block and the field name provided.
- get_blogs_of_user()Gets the sites a user belongs to.
- get_comment_author_url_link()Retrieves the HTML link of the URL of the author of the current comment.
- get_mu_plugins()Checks the mu-plugins directory and retrieve all mu-plugin files with any plugin data.
- get_plugins()Checks the plugins directory and retrieve all plugin files with plugin data.
- get_rest_url()Retrieves the URL to a REST endpoint on a site.
- is_email_address_unsafe()Checks an email address against a list of banned domains.
- is_serialized_string()Checks whether serialized data is of string type.
- is_wp_version_compatible()Checks compatibility with the current WordPress version.
- register_block_type_from_metadata()Registers a block type from the metadata stored in the `block.json` file.
- render_block_core_button()Renders the `core/button` block on the server,
- render_block_core_latest_posts()Renders the `core/latest-posts` block on server.
- render_block_core_rss()Renders the `core/rss` block on server.
- set_screen_options()Saves option for number of rows when listing posts, pages, comments, etc.
- upgrade_682()Executes changes made in WordPress 6.8.2.
- wp_add_trashed_suffix_to_post_name_for_post()Adds a trashed suffix for a given post.
- wp_fix_server_vars()Fixes `$_SERVER` variables for various setups.
- wp_get_active_and_valid_plugins()Retrieves an array of active and valid plugin files.
- wp_get_active_network_plugins()Returns array of network plugin files to be included in global scope.
- wp_get_code_editor_settings()Generates and returns code editor settings.
- wp_get_installed_translations()Gets installed translations.
- wp_get_mu_plugins()Retrieves an array of must-use plugin files.
- wp_is_client_side_media_processing_enabled()Checks whether client-side media processing is enabled.
- wp_kses_one_attr()Filters one HTML attribute and ensures its value is allowed.
- wp_render_background_support()Renders the background styles to the block wrapper.
- wp_render_dimensions_support()Renders server-side dimensions styles to the block wrapper.
- wp_version_check()Checks WordPress version against the newest version.
- wp_widget_rss_output()Displays the RSS entries in a list.
- wptexturize()Replaces common plain text characters with formatted entities.
Source code
function str_ends_with( $haystack, $needle ) { if ( '' === $haystack ) { return '' === $needle; } $len = strlen( $needle ); return substr( $haystack, -$len, $len ) === $needle; }Changelog
Introduced in 5.9.0. Unchanged from 6.7.7 through 7.1.0.
Signature, return type and hooks compared across 5 parsed releases.
About this page
- Parsed data
- Generated from the wordpress-develop 7.1.0 tag, from
src/wp-includes/compat.php, and regenerated for each WordPress release so it tracks the code rather than a snapshot of it. - Corrections
- Something wrong on this page? Report it and it gets fixed in the next regeneration.