PHP str_contains() Function – Complete Guide with Examples

When working with strings in PHP, developers often need to check whether a particular word, phrase, character, or piece of text exists inside another string. PHP provides the str_contains() function to make this type of check simple and readable.

PHP str_contains() function tutorial with syntax and string search examples

PHP str_contains() Function – Check Whether a String Contains a Substring

The str_contains() function was introduced in PHP 8.0 and provides a straightforward way to determine whether a string contains another string. Instead of manually using position-based string functions for a simple presence check, you can use str_contains() and receive a boolean result.

In this complete guide, you will learn what str_contains() does, how its syntax works, how to handle its return value, and how to use it in practical PHP applications. We will also cover common mistakes, real-world use cases, comparisons with other string functions, and best practices.

What is str_contains() in PHP?

The PHP str_contains() function checks whether a given substring exists within another string. It returns true when the substring is found and false when it is not found.

This function is useful when you only need to know whether some text exists inside a string. You do not need the exact position of the substring because the result is simply a boolean value.

For example, if you have a sentence containing the word PHP, you can use str_contains() to check whether the word exists.

<?php

  $text = "PHP is a popular server-side programming language.";

  if (str_contains($text, "PHP")) {
      echo "PHP was found.";
  } else {
      echo "PHP was not found.";
  }

?>

Output:PHP was found

Here, str_contains() checks whether "PHP" exists inside the $text string. Because it exists, the function returns true.

Why Use str_contains() in PHP?

The main reason to use str_contains() is simplicity. When your application only needs to know whether one string contains another string, a boolean result is usually easier to understand than checking a numeric string position.

Before PHP 8.0, developers commonly used functions such as strpos() for this type of check. Although strpos() can still be useful when the position is required, str_contains() makes a simple contains check more expressive.

  • It clearly communicates that you are checking for the presence of text.
  • It returns a simple boolean value.
  • It makes conditional statements easier to read.
  • It is useful for validation and filtering logic.
  • It works with both ASCII and binary-safe strings.
  • It avoids unnecessary position handling when you only need a yes/no result.

PHP str_contains() Syntax

The syntax of the str_contains() function is:

str_contains(string $haystack, string $needle): bool

The function accepts two required string parameters. The first parameter is the complete string that you want to search, while the second parameter is the text you want to find.

Parameter Description
$haystack The string in which PHP will search.
$needle The substring that you want to search for.

The function returns a boolean value: true if the needle is found and false otherwise.

Parameters Explanation

1. $haystack

The $haystack parameter contains the complete string that you want to search. It can be a simple string, a variable, a value returned from another function, or text retrieved from a database or request.

<?php

  $message = "Welcome to RaysCoding PHP tutorials.";

  $result = str_contains($message, "PHP");

  var_dump($result);

?>

Output:bool(true)

In this example, $message is the haystack because it contains the complete text being searched.

2. $needle

The $needle parameter contains the substring that you want to find inside the haystack.

<?php

  $message = "Welcome to RaysCoding PHP tutorials.";

  $keyword = "RaysCoding";

  $result = str_contains($message, $keyword);

  var_dump($result);

?>

Output:bool(true)

Here, "RaysCoding" is the needle because it is the text being searched for.

Return Value of str_contains()

The str_contains() function returns a boolean value. It returns true when the specified substring is present in the haystack and false when it is not present.

Condition Return Value
Substring exists true
Substring does not exist false
Needle is an empty string true

Because the result is boolean, str_contains() works naturally with if, else, ternary expressions, and other conditional logic.

Basic Example of str_contains() in PHP

Let's start with a simple example where we check whether a sentence contains the word Laravel.

<?php

  $text = "Laravel is a PHP framework.";

  if (str_contains($text, "Laravel")) {
      echo "The text contains Laravel.";
  } else {
      echo "Laravel was not found.";
  }

?>

Output: The text contains Laravel.

Explanation: The string stored in $text contains the word Laravel. Therefore, str_contains() returns true, and the first part of the if statement is executed.

Example: When the Substring Is Not Found

You can also use str_contains() to handle the situation where the requested text does not exist.

<?php

  $text = "PHP is used for web development.";

  if (str_contains($text, "Python")) {
      echo "Python was found.";
  } else {
      echo "Python was not found.";
  }

?>

Output: Python was not found.

Explanation: The word Python does not occur in the string, so the function returns false. The else block is therefore executed.

Case Sensitivity in str_contains()

One important point to remember is that str_contains() is case-sensitive. This means uppercase and lowercase letters are treated as different characters.

<?php

  $text = "I am learning PHP.";

  var_dump(str_contains($text, "PHP"));
  var_dump(str_contains($text, "php"));

?>

Output:

bool(true)
bool(false)

Explanation: The original string contains PHP with uppercase letters. It does not contain the lowercase version php. Therefore, the first search succeeds while the second search fails.

If your application needs a case-insensitive search, you should normalize the strings before using str_contains(), for example by converting both values to lowercase.

Case-Insensitive Search with strtolower()

PHP does not provide a case-insensitive version of str_contains(). A common approach is to convert both the haystack and needle to the same case before performing the search.

<?php

  $text = "Welcome to PHP Development.";

  $search = "php";

  if (str_contains(strtolower($text), strtolower($search))) {
      echo "The text contains PHP.";
  } else {
      echo "PHP was not found.";
  }

?>

Output: The text contains PHP.

Explanation: Both strings are converted to lowercase before the comparison. The original uppercase PHP therefore becomes php, allowing the search to succeed.

For Unicode-heavy or multilingual applications, be careful with simple case conversion and consider appropriate multibyte or locale-aware handling where required.

Checking an Empty String

An important behavior of str_contains() is that searching for an empty string returns true. This can matter when the search value comes from user input, a configuration value, or another dynamic source.

<?php

  $text = "PHP programming";
  $search = "";

  var_dump(str_contains($text, $search));

?>

Output: bool(true)

Explanation: An empty string is considered to occur in every string. If an empty search value is not meaningful for your application, validate it before calling str_contains().

Advanced Example: Checking Multiple Keywords

In real applications, you may need to check whether a text contains one of several keywords. You can combine str_contains() with conditional operators to build this type of logic.

<?php

  $message = "Your order has been shipped successfully.";

  if (
      str_contains($message, "order") ||
      str_contains($message, "shipped")
  ) {
      echo "The message contains an order-related keyword.";
  } else {
      echo "No matching keyword was found.";
  }

?>

Output: The message contains an order-related keyword.

Explanation: The code checks for two different words. Because the message contains both order and shipped, the condition evaluates to true.

Advanced Example: Filtering User Messages

Another practical use is checking submitted text for specific terms before processing it further. This can be useful for simple application rules, routing, or content classification.

<?php

  $message = "I need help with my PHP API.";

  if (str_contains(strtolower($message), "api")) {
      echo "This message is related to an API.";
  } else {
      echo "This message is not related to an API.";
  }

?>

Output: This message is related to an API.

Explanation: The message is converted to lowercase and then checked for the word api. This allows the example to match different capitalization styles such as API, Api, or api.

For security-sensitive filtering, however, simple substring matching should not be treated as a complete security mechanism. Validation and authorization should be handled separately.

Step-by-Step Code Explanation

Consider this example:

<?php

  $title = "PHP Laravel Tutorial";

  $keyword = "Laravel";

  if (str_contains($title, $keyword)) {
      echo "Keyword found.";
  } else {
      echo "Keyword not found.";
  }

?>

Step 1: The $title variable stores the string that we want to search.

Step 2: The $keyword variable stores the substring that we want to find.

Step 3: str_contains($title, $keyword) searches for the keyword inside the title.

Step 4: If the keyword exists, the function returns true.

Step 5: The if statement then displays Keyword found..

Output: Keyword found.

Real-World Use Cases of str_contains()

The str_contains() function is useful in many practical PHP applications where you only need to determine whether some text exists.

  • Search filters: Check whether a product name or description contains a requested keyword.
  • URL handling: Detect whether a URL contains a particular path or query fragment.
  • Form validation: Check whether submitted text contains an expected value.
  • Message processing: Detect keywords in support messages, notifications, or application logs.
  • Content classification: Identify simple categories based on keywords.
  • File processing: Check filenames or text content for known extensions or patterns.
  • Application routing: Perform simple text-based decisions based on known values.

str_contains() vs strpos()

Both str_contains() and strpos() can be used to determine whether a substring exists, but they serve slightly different purposes.

Feature str_contains() strpos()
Purpose Checks whether a substring exists Finds the position of a substring
Return type Boolean Integer or false
PHP version PHP 8.0+ Available in older PHP versions
Best for Simple presence checks When the position is required
Readability for contains checks Very direct Requires additional comparison logic

If your only requirement is to know whether a substring exists, str_contains() communicates that intention directly. If you need the actual position of the substring, strpos() is more appropriate.

You can also read our existing PHP strlen() function tutorial to learn how PHP works with string length.

str_contains() vs str_starts_with() vs str_ends_with()

PHP 8.0 introduced several convenient string functions that make common string checks easier to read. Each function answers a different question.

Function What it checks
str_contains() Whether a string contains a specific substring
str_starts_with() Whether a string starts with a specific substring
str_ends_with() Whether a string ends with a specific substring

Use str_contains() when the substring can appear anywhere in the string. Use the other functions when the location of the match matters.

Common Mistakes with str_contains()

1. Forgetting That the Function Is Case-Sensitive

A common mistake is expecting str_contains() to treat uppercase and lowercase text as identical. It does not. PHP and php are different values during a normal search.

2. Using strpos() Logic Unnecessarily

If you only need a boolean result, using position-based logic can make your code more complicated than necessary. str_contains() is designed specifically for this type of check.

3. Forgetting the Empty String Behavior

An empty needle returns true. If your search value comes from dynamic input, check that it contains a meaningful value before searching.

4. Using It on Unsupported PHP Versions

str_contains() was introduced in PHP 8.0. Applications running older PHP versions need a compatible alternative such as strpos().

5. Treating Simple Keyword Matching as Security

A substring check should not be used as a replacement for authentication, authorization, proper input validation, or security controls. It only answers whether a sequence of characters exists.

Best Practices for str_contains()

  • Use str_contains() when you only need a true or false answer.
  • Remember that the comparison is case-sensitive.
  • Normalize both strings when your application requires case-insensitive matching.
  • Validate dynamic search values before performing the check.
  • Use strpos() when you actually need the substring position.
  • Use dedicated validation or pattern-matching tools when simple substring matching is not sufficient.
  • Keep string checks readable instead of creating unnecessarily complicated conditions.
  • Make sure your production application runs a PHP version that supports the function.

Performance & Security Notes

str_contains() is designed for straightforward substring checks and is generally appropriate for normal string-search operations. However, the cost of searching naturally depends on the size of the strings and how frequently the operation is performed.

For normal web application logic, checking a product name, title, message, URL, or configuration value is not usually a performance concern.

For very large strings or extremely high-frequency processing, avoid unnecessary repeated searches and consider whether the data can be processed more efficiently.

From a security perspective, str_contains() should not be considered an input-security mechanism. Never rely on a simple substring check to authorize users, prevent attacks, or validate sensitive data.

For security-sensitive input, use proper validation, escaping, authorization, and framework-level security mechanisms appropriate to the application.

Related PHP String Functions

PHP provides many functions for working with strings. If you are learning PHP string handling, the following already-published tutorials on RaysCoding can help you continue your learning:

These tutorials are part of the broader PHP string-function learning path on RaysCoding.

Frequently Asked Questions About str_contains()


What does str_contains() do in PHP?

The PHP str_contains() function checks whether a specified substring exists inside another string. It returns true when the substring is found and false when it is not found.


Is str_contains() case-sensitive in PHP?

Yes. The str_contains() function is case-sensitive. For example, searching for php will not match PHP. If you need case-insensitive behavior, you can normalize both strings before performing the search.


Which PHP version introduced str_contains()?

The str_contains() function was introduced in PHP 8.0. Applications running older PHP versions should use an appropriate alternative such as strpos() when necessary.


What does str_contains() return?

str_contains() returns a boolean value. It returns true if the needle exists in the haystack and false if the needle cannot be found.


What happens when the needle is an empty string?

When the needle is an empty string, str_contains() returns true. If the search value comes from dynamic input, validate it first if an empty value should not be accepted by your application.

Conclusion

The PHP str_contains() function provides a clean and readable way to check whether one string contains another string. Its boolean return value makes it especially useful for conditional statements, validation logic, filtering, message processing, and other everyday PHP tasks.

The most important things to remember are that str_contains() requires a haystack and a needle, returns true or false, is case-sensitive, and is available from PHP 8.0 onward.

If you are learning PHP string functions, practice by checking words in sentences, validating user input, filtering messages, and processing application data. Once you understand str_contains(), the next useful functions to learn are str_starts_with() and str_ends_with(), which handle beginning and ending string checks.

Post a Comment

Previous Post Next Post