str_contains( string $haystack, string $needle ): bool
- Since
- 5.9.0
- Source
wp-includes/compat.php:499
Checks whether one string appears anywhere inside another, returning a boolean instead of the mixed offset that strpos() returns. It exists as a compatibility shim for the native PHP 8.0 str_contains(), so plugin and theme code can call it safely on any PHP version WordPress supports. Pair it with str_starts_with() or str_ends_with() when the match has to be anchored rather than anywhere in the string.
str_contains() function added in PHP 8.0.Description
Performs a case-sensitive check indicating if needle is contained in haystack.
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
$needleis in$haystack, 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.
Find posts whose title contains a keyword
Loop over the sample posts and print only the ones whose title contains a given word.
$keyword = 'world';
$matches = array();
for ( $post_id = 1; $post_id <= 5; $post_id++ ) {
$title = get_the_title( $post_id );
if ( '' !== $title && str_contains( $title, $keyword ) ) {
$matches[] = $title;
}
}
if ( $matches ) {
echo 'Titles containing "' . esc_html( $keyword ) . '": ' . esc_html( implode( ', ', $matches ) );
} else {
echo 'No titles contained "' . esc_html( $keyword ) . '".';
}get_the_title() returns an empty string for a missing post ID, so that case is skipped rather than crashing.
Detect whether a stored price includes a decimal point
Read the price meta value already stored on post 2 and check its format before formatting it for display.
$price = get_post_meta( 2, 'price', true );
if ( '' === $price ) {
echo 'Post 2 has no price meta set.';
} elseif ( str_contains( $price, '.' ) ) {
echo 'Price "' . esc_html( $price ) . '" already includes a decimal value.';
} else {
echo 'Price "' . esc_html( $price ) . '" is a whole number, appending .00.';
}Common problems and fixes · 3
- Why does str_contains() return true when I search for an empty string?
- Why doesn't str_contains() match when the case is different?
- Do I still need to call str_contains() on servers running PHP 8 or newer?
Why does str_contains() return true when I search for an empty string?
Why doesn't str_contains() match when the case is different?
Do I still need to call str_contains() on servers running PHP 8 or newer?
Alternatives and related functions
str_starts_with- When the substring has to be at the very beginning of the string rather than anywhere inside it.
str_ends_with- When the substring has to be at the very end of the string rather than anywhere inside it.
strpos- When you need to know the numeric position of the match, not just whether it exists.
stripos- When the search needs to ignore case instead of matching exactly like str_contains() does.
Performance profile
How much work a call to str_contains() 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
- 5–7
- Plugin surface
- None
- Called by
- 50
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 8.
Nothing here hands control to plugin code.
50 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_contains() can have, taken from its control-flow graph on PHP 8.5.
| When | Instructions | Calls it makes |
|---|---|---|
| always | 5–7 | none |
Across PHP versions
| PHP | Compiled | Executed | Branches | Notes |
|---|---|---|---|---|
| 8.6-dev | 8 | 5–7 | 1 | |
| 8.5 | 8 | 5–7 | 1 | |
| 8.4 | 8 | 5–7 | 1 | 3 fewer instructions than PHP 8.3 |
| 8.3 | 11 | 5–10 | 1 | |
| 8.2 | 11 | 5–10 | 1 | |
| 8.1 | 11 | 5–10 | 1 | |
| 7.4 | 11 | 5–10 | 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 · 50
- Automatic_Upgrader_Skin::feedback()Stores a message about the upgrade.
- Bulk_Upgrader_Skin::feedback()Displays a message about the update.
- Core_Upgrader::should_update_to_version()Determines if this WordPress Core version should update to an offered version or not.
- Core_Upgrader::upgrade()Upgrades WordPress core.
- Custom_Image_Header::js_1()Displays JavaScript based on Step 1 and 3.
- Custom_Image_Header::step_1()Displays first step of custom header image page.
- PO::poify()Formats a string in PO-style
- Request::getUri()Gets the request URI.
- WP::handle_404()Set the Headers for 404, if nothing is found for requested URL.
- WP::parse_request()Parses the request to find the correct WordPress query.
- WP::send_headers()Sends additional HTTP headers for caching, content type, etc.
- WP_Ajax_Upgrader_Skin::error()Stores an error message about the upgrade.
Show all 50
- WP_Automatic_Updater::after_core_update()Checks whether to send an email and avoid processing future updates after attempting a core update.
- WP_Automatic_Updater::run()Kicks off the background update process, looping through all pending updates.
- WP_Block_Processor::normalize_block_type()Normalizes a block name to ensure that missing implicit “core” namespaces are present.
- WP_Block_Styles_Registry::register()Registers a block style for the given block type.
- WP_Comment_Query::get_comment_ids()Used internally to get a list of comment IDs matching the query vars.
- WP_Customize_Manager::_publish_changeset_values()Publishes the values of a changeset.
- WP_Date_Query::validate_column()Validates a column name parameter.
- WP_Font_Face::build_font_face_css()Builds the font-family's CSS.
- WP_Font_Face_Resolver::maybe_parse_name_from_comma_separated_list()Parse font-family name from comma-separated lists.
- WP_Font_Utils::sanitize_font_family()Sanitizes and formats font family names.
- WP_HTML_Processor::serialize_token()Serializes the currently-matched token.
- WP_HTML_Tag_Processor::parse_next_tag()Parses the next tag.
- WP_HTML_Tag_Processor::set_modifiable_text()Sets the modifiable text for the matched token, if matched.
- WP_HTTP_Proxy::send_through_proxy()Determines whether the request should be sent through a proxy.
- WP_Http::block_request()Determines whether an HTTP API request to the given URL should be blocked.
- WP_Http::is_ip_address()Determines if a specified string represents an IP address or not.
- WP_Http::processHeaders()Transforms header string into an array.
- WP_Icons_Registry::register()Registers an icon.
- WP_Interactivity_API::process_directives()Processes the interactivity directives contained within the HTML content and updates the markup accordingly.
- WP_MS_Sites_List_Table::prepare_items()Prepares the list of sites for display.
- WP_Meta_Query::get_sql()Generates SQL clauses to be appended to a main query.
- WP_Plugin_Dependencies::convert_to_slug()Converts a plugin filepath to a slug.
- WP_Plugin_Install_List_Table::prepare_items()
- WP_Post_Type::remove_rewrite_rules()Removes any rewrite rules, permastructs, and rules for the post type.
- WP_Query::generate_cache_key()Generates cache key.
- WP_Query::generate_postdata()Generates post data.
- WP_Query::get_posts()Retrieves an array of posts based on query variables.
- WP_Query::parse_query()Parses a query string and sets query type booleans.
- WP_Query::parse_tax_query()Parses various taxonomy related query vars.
- WP_REST_Attachments_Controller::get_filename_from_disposition()Parses filename from a Content-Disposition header value.
- WP_REST_Autosaves_Controller::get_items()Gets a collection of autosaves using wp_get_post_autosave.
- WP_REST_Plugins_Controller::create_item()Uploads a plugin and optionally activates it.
- WP_REST_Plugins_Controller::does_plugin_match_request()Checks if the plugin matches the requested parameters.
- WP_REST_Request::get_content_type()Retrieves the Content-Type of the request.
- WP_REST_Server::get_data_for_route()Retrieves publicly-visible data for the route.
- WP_REST_Users_Controller::check_user_password()Check a user password for the REST API.
- WP_Rewrite::add_rule()Adds a rewrite rule that transforms a URL structure to a set of query vars.
- WP_Rewrite::generate_rewrite_rules()Generates rewrite rules from a permalink structure.
Source code
function str_contains( $haystack, $needle ) { if ( '' === $needle ) { return true; } return false !== strpos( $haystack, $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.