PHP str_contains() Function

PHP

PHP str_contains() - Check if String Contains

SEO Description: Learn PHP str_contains() function. Determine if a string contains a given substring.

The str_contains() function is an essential tool in PHP for checking whether a string contains a specific substring. Simple and readable, it allows developers to efficiently verify substring presence without resorting to complex string manipulation functions. In this tutorial, we’ll explore how to use str_contains(), complete with practical examples, best practices, common pitfalls, and interview questions to help solidify your understanding.

Prerequisites

  • Basic familiarity with PHP syntax and string handling.
  • PHP version 8.0.0 or higher (the str_contains() function was introduced in PHP 8).
  • Access to a web server or PHP CLI environment for testing code snippets.

Setup Steps

  1. Check PHP Version: Ensure your PHP version is 8.0.0 or newer.

    php -v
  2. Set up your environment: Use any text editor or IDE that supports PHP syntax highlighting.

    Examples can be tested on local servers like XAMPP, MAMP, or via command line.

  3. Create your PHP file: For instance str_contains_example.php.

  4. Write and run code snippets shown in this tutorial.

What is PHP str_contains()?

The str_contains() function checks whether a string contains a specified substring. It returns a boolean true if found, otherwise false. It offers a straightforward and readable solution compared to using functions like strpos() which require additional comparison logic.

Function Signature

bool str_contains(string $haystack, string $needle)
  • $haystack: The string to search in.
  • $needle: The substring to search for.

Basic Examples

Example 1: Simple substring check

<?php
$text = "Hello, welcome to the PHP tutorial.";
$search = "PHP";

if (str_contains($text, $search)) {
    echo "The text contains '$search'!";
} else {
    echo "The substring '$search' was not found.";
}
?>

Output: The text contains 'PHP'!

Example 2: Case sensitivity demonstration

<?php
$text = "Hello, Welcome To PHP.";
$search = "php";

if (str_contains($text, $search)) {
    echo "Found substring!";
} else {
    echo "Substring not found.";
}
?>

Output: Substring not found.

Note: str_contains() is case-sensitive.

Example 3: Using in conditional statements

<?php
$userInput = "apple pie";
if (str_contains($userInput, "apple")) {
    echo "User likes apple products.";
}
?>

Output: User likes apple products.

Best Practices

  • Use for quick substring detection: str_contains() offers better readability and less chance of errors compared to strpos() for existence checks.
  • Be mindful of case sensitivity: Since this is case-sensitive, transform strings with strtolower() if a case-insensitive check is required.
  • Check PHP version compatibility: If you support PHP versions below 8, consider polyfills or use strpos() !== false as alternative.
  • Handle empty needles: Passing an empty string as the needle will always return true. Validate input if needed.

Common Mistakes

  • Ignoring PHP version compatibility and using str_contains() on versions <8.0, which will cause fatal errors.
  • Assuming str_contains() is case-insensitive and thus getting unexpected false results.
  • Poor handling of empty needles; an empty needle always returns true, which might cause logical bugs.
  • Misusing the return value β€” for example, treating it as an integer position rather than a boolean.

Interview Questions

Junior Level

  • Q1: What does the str_contains() function return?
    A: It returns true if the substring is found in the string, otherwise false.
  • Q2: Is the str_contains() function case-sensitive?
    A: Yes, str_contains() is case-sensitive.
  • Q3: From which PHP version is str_contains() available?
    A: It is available from PHP 8.0.0 onwards.
  • Q4: What happens if you pass an empty string as the substring to str_contains()?
    A: It will always return true.
  • Q5: Can str_contains() be used to find the position of a substring in a string?
    A: No, it only returns a boolean indicating presence or absence.

Mid Level

  • Q1: How would you implement a case-insensitive str_contains() check?
    A: Using str_contains(strtolower($haystack), strtolower($needle)).
  • Q2: Why might you prefer str_contains() over strpos() for substring checks?
    A: It's more readable, returns a boolean directly, and avoids the need to compare against false.
  • Q3: What will happen if you use str_contains() with non-string types for parameters?
    A: PHP will try to convert them to strings, but it's recommended to ensure strings for expected behavior.
  • Q4: How can you handle substring searches if your PHP environment is below 8.0?
    A: Use a polyfill or strpos() !== false as an alternative.
  • Q5: Can str_contains() be used in multi-byte string contexts reliably?
    A: Yes, because it operates on strings, but always be cautious with encoding and use multi-byte functions if manipulating strings.

Senior Level

  • Q1: Explain how str_contains() improves code readability and maintenance in PHP projects.
    A: It abstracts away manual position checks, reduces boilerplate (no need to compare strpos() against false), making substring checks more expressive and less error-prone.
  • Q2: Discuss how using str_contains() could impact performance compared with strpos().
    A: Performance differences are negligible; however, str_contains() focuses on clarity over returning position, so for presence checks it’s optimized and preferred.
  • Q3: How would you create a polyfill for str_contains() for PHP <8.0?
    A: Define a function that uses strpos($haystack, $needle) !== false and returns boolean accordingly.
  • Q4: In a multi-language web app, what considerations should you keep when using str_contains()?
    A: Ensure consistent string encoding across inputs, watch for case and locale considerations, and consider using multi-byte string functions if needed for non-ASCII characters.
  • Q5: Can str_contains() be used to validate against malicious input injection? Why or why not?
    A: Not directly; while it can detect substring presence, security validations require more thorough sanitization and escaping beyond simple substring checks.

Frequently Asked Questions (FAQ)

Q1: What does str_contains() return if the substring is empty?

It always returns true if the needle (substring) is an empty string.

Q2: Is str_contains() case-insensitive?

No, it performs case-sensitive checks. For case-insensitive searches, you need to convert both strings to the same case.

Q3: Can I use str_contains() to find the position of a substring?

No, str_contains() only indicates presence with a boolean. Use strpos() to get the actual position.

Q4: How do I check if a string does NOT contain a substring?

You can use the NOT operator with str_contains(), for example: !str_contains($haystack, $needle).

Q5: What PHP versions support str_contains()?

It is supported in PHP 8.0.0 and newer.

Conclusion

The PHP str_contains() function is a simple and readable way to detect substrings within strings. By returning a straightforward boolean result, it simplifies common tasks that previously required more verbose checks using strpos(). However, developers should be mindful of its case sensitivity, behavior with empty needles, and PHP version compatibility. Leveraging str_contains() improves code clarity and reduces bugs in substring detection scenarios.

Try it out in your projects today to write cleaner, more expressive PHP string handling code!