Introduction to PHP str_contains
In PHP string manipulation, PHP 8 introduced a valuable addition: the str_contains() function. It simplifies checking if a string (a substring or needle) exists within another larger string (called the haystack). This function streamlines the process of locating substrings within strings. Previously, developers commonly employed functions like strpos for this task. str_contains elevates the approach by offering a clear and succinct method to ascertain the presence of a specific substring (often referred to as a needle) within a larger string (the haystack). It conducts a case-sensitive search and returns a boolean value, indicating success (true) if the substring is found within the haystack or failure (false) if not. This function even caters to empty substrings, returning true if an empty string is in the haystack. Ultimately, str_contains enhances code readability by providing a more intuitive and expressive way to check for substring existence. This simplifies development and improves code maintainability for oneself and collaborators. The str_contains() function searches for case-sensitive substrings. It is used in various string manipulation tasks, like validation, search operations, conditional logic, etc.
Table of Contents
Key takeaways
- This str_contains() function checks if a string contains a substring.
- It takes two function parameters: haystack and needle.
- It returns a boolean value: true or false.
- It is a case-sensitive function.
- It always returns true for an empty search.
- It is a predefined function in PHP 8 and higher versions.
- Other functions similar to this function are: stripos(), str_ends_with(), str_starts_with(), strrpos(), and strripos().
Syntax and parameters (with Example)
The syntax of the str_contains() function in PHP:
str_contains(string $haystack, string $needle): bool
There are two function parameters: $haystack and $needle. In programming, the $haystack represents the string you search within, and the $needle is the substring you seek. The function returns a boolean value: actual if the $needle is found within the $haystack and false otherwise.
For example,
<?php
$string = "EDUCBA is Best Online Training & Video Courses Certification";
$searchTerm = "EDUCBA";
if (str_contains($string, $searchTerm)) {
echo "The string contains the search term.";
} else {
echo "The string does not contain the search term.";
}
?>
Output:
When you run this code, it will output: “The string contains the search term.” It is because the substring “EDUCBA” is found within the string “EDUCBA is Best Online Training & Video Courses Certification.”
How str_contains() Works
The str_contains() function uses a linear approach. It is a simple and efficient algorithm for searching as the function iterates through each character of the haystack string. It compares a substring of the same length starting from the current position to the needle string. Suppose the substring matches the needle string. Then, the function returns true. Otherwise, it continues iterating until the end of the haystack string is reached, at which point it returns false. Thus, O(n+m) is the time complexity, where n and m are the needle string and haystack lengths, respectively.
Compatibility and Version Support
The str_contains() function was introduced in PHP 8, so it is available only in PHP versions 8 and above. Therefore, if you try to use this function in an earlier version of PHP, you should have a PHP environment running version 8 or later on your machine. It will give a fatal error due to an undefined function. It works on Linux, Windows, macOS, etc.
For example,
<?php
// Check PHP version compatibility
if (version_compare(PHP_VERSION, '8.0.0') < 0) {
echo "Error: Your PHP version is too old. str_contains() requires PHP 8 or later.";
// To exit the script
exit();
}
// Example usage of str_contains() function
$string = "EDUCBA is Best Online Training & Video Courses Certification";
$searchTerm = "educba";
// Check if the string contains the search term using str_contains()
if (str_contains($string, $searchTerm)) {
echo "The string contains the search term.";
} else {
echo "The string does not contain the search term.";
}
?>
Suppose you execute this program in an earlier version of PHP 8. It will give the following message defined in the code:
Otherwise, this code executes successfully if you have PHP 8 or above. The output is:
Note that since str_contains() is case-sensitive, it will not match the term “educba” with “EDUCBA”.
Performance Considerations
The str_contains() function makes it easy to search substrings. Since it uses linear search, the length of the input string and the substring being searched determine how well it performs. It performs well even with large strings and search terms and provides efficient performance in most use cases. However, it is important to consider factors. These factors include string length, frequency of function calls, and overall application requirements when evaluating performance.
Common Pitfalls and Errors
PHP’s str_contains() function has various pitfalls and errors. You should carefully use this function to avoid these pitfalls and mistakes. We have discussed some of them as follows.
1. Ignoring Case Sensitivity
This str_contains() is a case-sensitive function. If you try to search for a term in lowercase in a given string, it is uppercase. It will not return true.
For example,
<?php
$string = "EduCBA is a nice platform!";
$searchTerm = "educba";
if (str_contains($string, $searchTerm)) {
echo "Found!"; // This won't be printed because the case doesn't match.
} else {
echo "Not Found!";
}
?>
Output:
You can solve this case-sensitivity issue by converting both strings to either lowercase or uppercase, but not both. You should convert these before starting the search.
The above code will return true as we converted both strings to lowercase before starting the search. The search term “educba” will now match the string “EduCBA is a nice platform!”.
2. Assuming Empty String Match
Note that if you try to search for an empty string in a string, it will always match. But if you try to search for any substring other than an empty string in an empty string, it will return false.
For example,
<?php
$string = "";
$searchTerm = "educba";
if (str_contains(strtolower($string), strtolower($searchTerm))) {
echo "Found!"; // This won't be printed because the case doesn't match.
} else {
echo "Not Found!";
}
?>
In this code, we are searching for a non-empty string in an empty string. It will return false. The output will be as follows:
However, this logic needs to be corrected and updated for this edge case. We can resolve this issue using a non-empty condition. In the if condition, you should add $searchTerm != “.
<?php
$string = "";
$searchTerm = "educba";
if ($searchTerm != "" && str_contains(strtolower($string), strtolower($searchTerm))) {
echo "Found!"; // This won't be printed because the case doesn't match.
} else {
echo "Not Found!";
}
?>
Now, this logic is correct and will not produce unexpected results.
3. Not Handling False Positives
There can be multiple search term occurrences in the given string. We require the first occurrence of the search term in the string. The str_contains() function might need to be more accurate. For example,
<?php
$string = "Mississippi";
$searchTerm = "si";
if ($searchTerm != "" && str_contains(strtolower($string), strtolower($searchTerm))) {
echo "Found 'si' at the beginning."; // This might be misleading.
} else {
echo "Not Found!";
}
?>
It will return true if found in any position, but not necessarily in the first instance. The output is:
You can use PHP’s strpos() function to resolve this issue. If you need the exact location, strpos will return the position of the first occurrence. However, strpos() is less efficient than str_contains() because it requires more checks and searches. The str_contains() function is less time-consuming and performs more than PHP’s strpos() function.
4. Overlooking Regular Expressions
There is another flaw if you try to use the str_contains() function to search for some complex regular expression, like email and date format. Then, it may fail to give the correct result.
For example, we want to search for a mail address in the given string:
<?php
$string = "Valid email: [email protected]";
$searchTerm = "/\w+@\w+\.\w+/"; // Regular expression for email format
if (str_contains(strtolower($string), strtolower($searchTerm))) {
echo "Found a valid email."; // Inefficient for complex patterns.
} else {
echo "Not Found!";
}
?>
Note that the given string “Valid email: [email protected]” contains a valid email address. However, it returns false and results in “Not Found!”, which is not the correct result, as expected.
Output
To address this issue, we should use another PHP function, such as the preg_match() function. This function works well with complex regular expressions.
<?php
$string = "Valid email: [email protected]";
$searchTerm = "/\w+@\w+\.\w+/"; // Regular expression for email format
if (preg_match($searchTerm, strtolower($string))) {
echo "Found a valid email.";
} else {
echo "Not Found!";
}
?>
It will return true, and the result will be “Found a valid email.”. The output is:
Comparison with Similar Functions
There are various other functions similar to str_contains() functions in PHP, like strpos(), strstr(), etc. Note that the str_contains() function was introduced in PHP 8.
To determine where a substring appears for the first time within a string, use the strpos() function. It returns the position as an integer. If the substring is not found, it returns false. Suppose you know the exact position of the first occurrence of a substring within a string. Then, you can use the strpos() function in PHP. You can also use it to extract substrings and perform replacements on a given index. The syntax of the strpos() function is
strpos(string,find,start)
Where the start is optional, it is the index number from where to start the search. If it is negative, then it starts from last.
The strstr() function is similar to the strpos() function. It finds the first occurrence of a substring within a string. But it also returns the string after the first match. It is also case-sensitive. You can use the stristr() function to search for case-insensitive information. The syntax of the strstr() function is:
strstr(string,search,before_search)
Where before_search is optional, it is a boolean value. If it is true, it will also return the string before the first occurrence.
Consider this code example to compare the outputs of the above:
<?php
$string = "There is a website, named educba, which is best place to learn";
$searchTerm = "educba";
// Using str_contains()
if (str_contains($string, $searchTerm)) {
echo "The string contains the search term.\n";
} else {
echo "The string does not contain the search term.\n";
}
// Using strpos()
$position = strpos($string, $searchTerm);
if ($position !== false) {
echo "The substring starts at position: $position\n";
} else {
echo "The substring was not found.\n";
}
// Using strstr()
$subString = strstr($string, $searchTerm);
if ($subString !== false) {
echo "The substring starting from '$searchTerm' is: $subString\n";
} else {
echo "The substring was not found.\n";
}
?>
The output:
The comparisons of str_contains() vs. strpos() vs. strstr()
Feature | str_contains() | strpos() | strstr() |
Introduced in PHP | 8 | 4 | 4 |
Purpose | It checks if a string contains another string | It finds the position of the first occurrence | It finds the substring from the first occurrence |
Return Value | Boolean (true if found, false otherwise) | Integer (position of first occurrence) | String (from first occurrence to end) |
Case Sensitivity | Case-sensitive | Case-sensitive | Case-sensitive |
Needle Parameter | String | String or character | String or character |
Haystack Parameter | String | String | String |
Performance | Optimized for simple substring checks | It may be slower for large strings | It may be slower for large strings |
Use Case | Boolean checks for substring presence | Finding a position for substring extraction | Extracting substring from first occurrence |
Note
- The strrpos(), stripos(), and strripos() are related functions of strpos(). The strrpos() is case-sensitive, and the stripos() and strripos() are case-insensitive. The stripos() function returns the first occurrence, while the strrpos() and strripos() return the last occurrences.
- There are other functions like str_starts_with(), preg_match(), and preg_contains(). These are similar to the str_contains() function.
Use Cases and Practical Applications
There are various use cases of str_contains() in PHP.
- You can filter content based on keywords. It helps moderate user-generated content on forums, social media platforms, comment sections, etc.
- You can search query queries in a database of articles, products, documents., etc.
- You can match URL patterns and direct users to the appropriate page in web development.
- You can analyze large datasets and log files. It is used to identify trends, anomalies, errors in the data, etc.
- It can highlight important sections in a document and email if it contains a given keyword.
- Users’ preferences and actions can be used to create dynamic content, such as recommendations of articles, products, etc.
Filtering User Input
Consider a practical application of PHP’s str_contains() function. You can filter user input text in the feedback form filled out by users. You can filter abusive and spam words by searching for them in user input. For example,
<?php
// Feedback submitted by the user
$userFeedback = $_POST['feedback'];
// Prohibited words list
$prohibitedWords = array("spam", "inappropriate", "offensive");
// Check if the user feedback contains any prohibited words
foreach ($prohibitedWords as $word) {
if (str_contains(strtolower($userFeedback), strtolower($word))) {
echo "Your feedback contains prohibited words. Please revise it.";
// Other code here, like logging and submission
exit; // Exit the script to prevent further processing
}
}
// If no prohibited words are found, process the feedback
echo "Thank you for your feedback!";
?>
The output is:
When a user submits a feedback form using this code, we check if it contains any words from the prohibitedWords list using str_contains(). A message asking the user to edit it is displayed if feedback is found. Otherwise, it proceeds. This maintains the integrity of the feedback system.
Conclusion
The str_contains() function in PHP 8 can check if a string contains a specified substring. It uses a linear search approach with linear time complexity. However, it is case-sensitive. Various other similar functions of str_contains () exist, like str_starts_with(), strrpos(), and strripos (). The str_contains() function has some limitations. It is not valuable for complex regular expressions, like date and email format matches. You can use this function in keyword searching, content moderation, URL routing, dynamic content generation, etc.
Frequently Asked Questions (FAQs)
Q1: Can you use the str_contains() function to search multiple substrings within a string simultaneously?
Answer: No. You cannot use it to search multiple substrings within a string simultaneously; it can only search a single substring in a given string. However, you can use it to search various substrings simultaneously by looping through an array of substrings and checking each one individually.
Q2: Can you use the str_contains() function with substrings in binary data or non-textual content?
Answer: No. You should not use it to search with binary data or non-textual content because it is designed for text content. It can give the wrong results if you use binary data or non-textual content such as images or audio files.
Q3: Can you use the str_contains() function to search substrings within arrays or objects?
Answer: No. It can be used to search for substrings within text data types. It does not support searching within arrays or objects directly.
Recommended Articles
We hope that this EDUCBA information on “PHP str_contains()” was beneficial to you. You can view EDUCBA’s recommended articles for more information