Table of contents
1.
Introduction
2.
Properties
3.
Syntax
4.
Parameters
5.
Examples
5.1.
Example 1: Checking if a string contains a substring
5.2.
Example 2: Searching for multiple substrings
5.3.
Example 3: Case-insensitive substring search
6.
Alternate Function like str_contains()
6.1.
1. stripos()
6.1.1.
Syntax:
6.1.2.
Example
6.2.
2. strpos
6.2.1.
Syntax
6.2.2.
Example:
6.3.
3. strrpos()
6.3.1.
Syntax:
6.3.2.
Example:
7.
Frequently Asked Questions
7.1.
What is the difference between str_contains() & strpos()?
7.2.
Is str_contains() case-sensitive?
7.3.
Can str_contains() search for multiple substrings at once?
8.
Conclusion
Last Updated: Oct 27, 2024
Easy

PHP str_contains() Function

Author Sinki Kumari
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

PHP is a widely used server-side scripting language which is known for its extensive set of built-in functions that simplify various programming tasks. Among these functions, str_contains() is a useful tool for working with strings. Introduced in PHP 8.0, this function helps developers easily check if a string contains a specific substring, which makes it a convenient choice for text processing & string manipulation. 

PHP str_contains() Function

In this article, we'll discuss the str_contains() function in detail, like its properties, syntax, & parameters, with proper examples to show its use. 

Properties

The str_contains() function in PHP has the following properties:
 

1. Case-sensitive: str_contains() performs a case-sensitive search by default. It returns true only if the substring matches exactly, including the case of the characters.
 

2. Returns a boolean value: The function returns a boolean value - true if the substring is found within the string, & false otherwise.
 

3. Supports multiple character encodings: str_contains() works with various character encodings, ensuring compatibility with different languages & character sets.
 

4. Part of the string functions family: str_contains() belongs to the family of PHP string functions, which includes other useful functions like strpos(), substr(), & str_replace().
 

5. Requires PHP 8.0 or later: The str_contains() function was introduced in PHP 8.0. To use it, you need to have PHP 8.0 or a later version installed on your system.

Syntax

The syntax for using the str_contains() function in PHP is :

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


In this syntax : 

  • `str_contains()`: The name of the function.
     
  • `string $haystack`: The first parameter, which represents the string in which you want to search for the substring. It is prefixed with the `string` type, indicating that it expects a string value.
     
  • `string $needle`: The second parameter, which represents the substring you want to search for within the `$haystack`. It is also prefixed with the `string` type.
     
  • `: bool`: The return type of the function, which is a boolean value (`true` or `false`).
     

Note: To use the str_contains() function, you need to pass the string you want to search in (`$haystack`) as the first argument & the substring you want to find (`$needle`) as the second argument. The function will return `true` if the `$needle` is found within the `$haystack`, & `false` otherwise.

Parameters

The str_contains() function accepts two parameters:
 

1. `$haystack` (required):

   - Data type: string

   - Description: The string in which you want to search for the substring.

   - The `$haystack` parameter is the main string that you want to examine to determine if it contains the specified substring.
 

2. `$needle` (required):

   - Data type: string

   - Description: The substring you want to search for within the `$haystack`.

   - The `$needle` parameter represents the substring that you want to find within the `$haystack` string.


Both parameters are required for the str_contains() function to work correctly. The function will search for the exact occurrence of the `$needle` substring within the `$haystack` string.

It's important to note that the str_contains() function is case-sensitive. This means that it will only return `true` if the `$needle` substring matches exactly, including the case of the characters. If you want to perform a case-insensitive search, you can use the strcasecmp() function in combination with str_contains().

Let’s look at the examples to show the use of the parameters:

$haystack = "The quick brown fox jumps over the lazy dog";
// Searching for a substring
var_dump(str_contains($haystack, "quick"));
var_dump(str_contains($haystack, "slow"));
// Case-sensitivity
var_dump(str_contains($haystack, "Fox"));
var_dump(str_contains($haystack, "fox"));
// Empty strings
var_dump(str_contains($haystack, ""));
var_dump(str_contains("", ""));
You can also try this code with Online PHP Compiler
Run Code


Output

bool(true)
bool(false)
bool(false)
bool(true)
bool(true)
bool(true)


In the above examples, we demonstrate searching for different substrings within the `$haystack` string. The function returns `true` when the `$needle` substring is found and `false` when it's not present. We also showcase the function's case sensitivity and how it behaves with empty strings.

Examples

Let’s discuss a few examples to understand this more better : 

Example 1: Checking if a string contains a substring

$message = "Hello, how are you?";
if (str_contains($message, "how")) {
    echo "The message contains the word 'how'.";
} else {
    echo "The message does not contain the word 'how'.";
}
You can also try this code with Online PHP Compiler
Run Code


Output:

The message contains the word 'how'.


In this example, we have a string `$message` with the value "Hello, how are you?" We use the str_contains() function to check if the substring "how" exists within the `$message`. Since "how" is present in the string, the condition is true, and the corresponding message is echoed.

Example 2: Searching for multiple substrings

$text = "The sun rises in the east & sets in the west.";
$keywords = ["sun", "moon", "east", "north"];
foreach ($keywords as $keyword) {
    if (str_contains($text, $keyword)) {
        echo "The text contains the keyword '$keyword'." . PHP_EOL;
    } else {
        echo "The text does not contain the keyword '$keyword'." . PHP_EOL;
    }
}
You can also try this code with Online PHP Compiler
Run Code


Output:

The text contains the keyword 'sun'.
The text does not contain the keyword 'moon'.
The text contains the keyword 'east'.
The text does not contain the keyword 'north'.


In this example, we have a string `$text` & an array `$keywords` containing multiple substrings. We use a foreach loop to iterate over each keyword & check if it exists within the `$text` using the str_contains() function. The script outputs whether each keyword is found in the text or not.

Example 3: Case-insensitive substring search

$text = "The quick brown Fox jumps over the lazy dog.";
if (str_contains(strtolower($text), strtolower("fox"))) {
    echo "The text contains the word 'fox' (case-insensitive).";
} else {
    echo "The text does not contain the word 'fox' (case-insensitive).";
}
You can also try this code with Online PHP Compiler
Run Code


Output:

The text contains the word 'fox' (case-insensitive).


In this example, we showed a case-insensitive substring search. Since str_contains() is case-sensitive by default, we convert both the `$text` & the substring "fox" to lowercase using the strtolower() function before performing the search. This way, the search becomes case-insensitive, & the condition is true even though "fox" appears as "Fox" in the original text.Disadvantages of str_contains() Function

1. Case-sensitivity: By default, str_contains() performs a case-sensitive search. If you want to perform a case-insensitive search, you need to convert both the haystack & needle to the same case (e.g., using strtolower() or strtoupper()) before using str_contains(). This adds an extra step to the process.
 

2. No pattern matching: str_contains() only searches for an exact substring within the string. It doesn't support pattern matching or regular expressions. If you need to search for substrings based on patterns or more complex conditions, you'll need to use other functions like preg_match() or strpos().
 

3. Limited functionality: str_contains() only checks if a substring exists within a string. It doesn't provide information about the position of the substring or allow for replacing or manipulating the substring. For more advanced string operations, you may need to use other functions like strpos(), substr(), or str_replace().
 

4. Performance considerations: If you need to search for a large number of substrings within a string or perform searches on very large strings, the performance of str_contains() might not be optimal. In such cases, alternative approaches like using a lookup table or more efficient algorithms may be preferable.

Alternate Function like str_contains()

  1. Stripos
     
  2. Stropsf
     
  3. Strrpos

1. stripos()

Syntax:

stripos(string $haystack, string $needle, int $offset = 0): int|false


Example

$text = "Hello, World!";
$position = stripos($text, "world");
if ($position !== false) {
    echo "The substring 'world' was found at position $position (case-insensitive).";
} else {
    echo "The substring 'world' was not found (case-insensitive).";
}
You can also try this code with Online PHP Compiler
Run Code


Output:

The substring 'world' was found at position 7 (case-insensitive).

2. strpos

Syntax

strpos(string $haystack, string $needle, int $offset = 0): int|false

Example:

$text = "Hello, World!";

$position = strpos($text, "World");

if ($position !== false) {
    echo "The substring 'World' was found at position $position.";
} else {
    echo "The substring 'World' was not found.";
}
You can also try this code with Online PHP Compiler
Run Code


Output:

The substring 'World' was found at position 7.

3. strrpos()

Syntax:

strrpos(string $haystack, string $needle, int $offset = 0): int|false

Example:

$text = "Hello, World! Hello, PHP!";
$position = strrpos($text, "Hello");
if ($position !== false) {
    echo "The last occurrence of 'Hello' was found at position $position.";
} else {
    echo "The substring 'Hello' was not found.";
}
You can also try this code with Online PHP Compiler
Run Code


Output:

The last occurrence of 'Hello' was found at position 14.


In the examples :

  • stripos() is used to find the position of the first occurrence of a substring within a string, case-insensitively.
     
  • strpos() is used to find the position of the first occurrence of a substring within a string, case-sensitively.
     
  • strrpos() is used to find the position of the last occurrence of a substring within a string, case-sensitively.


The functions return the position of the substring if found or false if the substring is not found.

Frequently Asked Questions

What is the difference between str_contains() & strpos()?

str_contains() checks if a substring exists within a string & returns a boolean value, while strpos() returns the position of the first occurrence of the substring or false if not found.

Is str_contains() case-sensitive?

Yes, str_contains() performs a case-sensitive search by default. To perform a case-insensitive search, you can convert both the haystack & needle to the same case before using str_contains().

Can str_contains() search for multiple substrings at once?

No, str_contains() only searches for a single substring at a time. To search for multiple substrings, you need to use str_contains() multiple times or use alternative functions like preg_match() with regular expressions.

Conclusion

In this article, we discussed the str_contains() function in PHP, which allows us to check if a string contains a specific substring. We learned about its syntax, parameters, and usage through various examples. We also discussed the disadvantages of str_contains(), like case sensitivity and limited functionality. Moreover, we explained alternative functions like strpos(), strstr(), and preg_match () and their variations for different use cases. 

You can also check out our other blogs on Code360.

Live masterclass