Effortless String Checks in PHP with str_contains()

Published on | Reading time: 6 min | Author: Andrés Reyes Galgani

Effortless String Checks in PHP with str_contains()
Photo courtesy of Mitchell Luo

Table of Contents

  1. Introduction
  2. Problem Explanation
  3. Solution: The Power of the str_contains() Function
  4. Practical Application
  5. Potential Drawbacks and Considerations
  6. Conclusion
  7. Final Thoughts

Introduction

Have you ever felt overwhelmed by the sea of string manipulation functions in PHP? 😅 You're not alone! PHP comes packed with an arsenal of functions that can make string handling a breeze, but sometimes it can lead to confusion about which one to use for specific scenarios. Just picture this: you have a string containing too many elements, a mix of substrings, and you're looking for a simple, elegant way to determine if a particular substring exists within that string.

Many developers often resort to classic approaches by throwing in regular expressions or lengthy conditions that can complicate the code and reduce readability. 😱 But what if I told you that PHP has a hidden gem—an unexpected function that sheds light on string containment? Enter str_contains(): a straightforward way to check if a substring exists within a string.

In this post, we'll dive deeper into this lesser-known PHP function, exploring its utility, practicality, and the advantages it offers compared to previous methods. You may not just find this function useful; it could transform how you handle string comparison in your code! Let's bust some misconceptions and embrace cleaner, more efficient coding practices.


Problem Explanation

Before we jump headfirst into the advantages of str_contains(), let's address the problem that many PHP developers face—string containment checks. Often, developers use strpos() or preg_match() to determine whether a substring exists within a larger string.

Consider this traditional approach using strpos():

$haystack = "Hello, welcome to the PHP world!";
$needle = "PHP";

if (strpos($haystack, $needle) !== false) {
    echo "Substring found!";
} else {
    echo "Substring not found.";
}

Using strpos() does get the job done, but let's unpack its downsides. First, using !== false can be a bit cumbersome. Why? Because if strpos() returns 0, it means the substring is found at the beginning of the string, yet this value is falsy in PHP. Therefore, failing to handle such special cases might lead you to incorrect assumptions.

Meanwhile, utilizing preg_match() for our containment checks looks like this:

if (preg_match("/$needle/", $haystack)) {
    echo "Substring found!";
} else {
    echo "Substring not found.";
}

This might appear cleaner—until you remember your friend regex and how easy it is to trip into its complexity. In short, relying on traditional functions made string checks tedious and error-prone.


Solution: The Power of the str_contains() Function

So, where does str_contains() fit into this picture? Released in PHP 8.0, it allows you to determine if a string contains a given substring without the drawbacks associated with its predecessors. It employs a more straightforward syntax, which ultimately leads to enhanced readability. Here’s how you can utilize it:

$haystack = "Hello, welcome to the PHP world!";
$needle = "PHP";

if (str_contains($haystack, $needle)) {
    echo "Substring found!";
} else {
    echo "Substring not found.";
}

Simplifying the String Check Process:

  1. Readability: The syntax is clean and self-explanatory. It instantly conveys the intent of checking for a substring.
  2. Negligible Complexity: There's no need to worry about handling various return values; if it exists, it returns true—if not, false.
  3. No Regex Overheads: You skip the unnecessary regex overhead—making your checks efficient and straightforward.

Moreover, str_contains() plays harmoniously with other PHP string functions, allowing you to combine them effortlessly. For example, if you need to ensure case insensitivity, you can easily incorporate this function along with strtolower() for consistent results.

Here's an example that showcases case insensitivity:

$haystack = "Hello, welcome to the PHP world!";
$needle = "php";

if (str_contains(strtolower($haystack), strtolower($needle))) {
    echo "Substring found!";
} else {
    echo "Substring not found.";
}

This combines strtolower() and str_contains() flawlessly, demonstrating how PHP allows you to integrate functions for better code flow, while keeping the integrity intact.


Practical Application

Now that you see how delightful the str_contains() function is, let’s delve into real-world scenarios where this function shines. Imagine you're building a search feature for blog posts where users enter keywords, and you want to check if the keywords exist in the post titles or content.

Here’s an example of how str_contains() could help:

foreach ($posts as $post) {
    if (str_contains($post->title, $searchTerm)) {
        echo "Matching title found: " . $post->title;
    }
}

This code snippet effectively filters through your posts and shows relevant titles containing the search term—keeping your coding practical and efficient while improving readability for anyone who reviews your code later.

Another scenario would be implementing user input validation. You may want to ensure that specific strings, like certain keywords or commands, are part of a user's input before proceeding with processing. Here's how that could look:

$userInput = "Please run the clean command.";
$command = "clean";

if (str_contains($userInput, $command)) {
    // Execute the clean command
    echo "Executing clean command...";
}

By using str_contains(), you can ensure that command interpretation is straightforward and clear without convoluted logic.


Potential Drawbacks and Considerations

Despite its strengths, str_contains() is not without its potential drawbacks. One major point to consider is compatibility—str_contains() is only available in PHP 8.0 and above. If you're working with legacy systems confined to earlier PHP versions, this function will not be an option.

Additionally, the function is strictly a containment check, meaning it doesn't provide information about the position of the substring. If you need to know where the substring can be found for further actions (like extracting text), strpos() would be necessary.

To mitigate these drawbacks, it's essential to assess the PHP version during your development cycle. If you cannot upgrade to PHP 8.0 or higher, relying on traditional functions is still feasible but requires careful handling of the return values.


Conclusion

In today’s post, we uncovered the utility of the str_contains() function, a modern addition to PHP that simplifies string checking with elegance. Leveraging this function promotes code readability, efficiency, and maintainability while sidestepping the common pitfalls associated with its predecessors.

The beauty of str_contains() lies in its simplicity, allowing you to focus more on developing your application rather than getting bogged down by complex string logic. As we transition into an era of cleaner code practices and more maintainable solutions, it's essential to keep our toolkit updated with new features like this one.


Final Thoughts

Now it's your turn! Dive into your current projects and see how str_contains() can improve your string operation implementations. Whether you're refining user input validation or creating search functions, I'd love to hear how you've integrated this function into your code. Share your experiences or any alternative approaches in the comments below!

And don’t forget to subscribe for more expert tips and tricks on PHP and other technologies—let’s keep advancing our coding skills together!


Focus Keyword: PHP str_contains
Related Keywords: string manipulation PHP, PHP 8 string functions, strpos alternative PHP, PHP string contains function