PHP String Contains Substring Guide

Php string contains substring guide

When working with strings inside PHP, you'll likely need to compare one string against another. This very common task is a typical use case in nearly all PHP projects. Since PHP 8 this has gotten a lot easier with the function str_contains, but prior versions 7 and below require developers to learn and then remember to do this same task with either strpos or strstr functions. How does the PHP 8 function str_contains work, and what should we do if we're working on PHP 7 or below and are required to find strings inside other strings? We will explore both of these use cases, along with code examples to show you the way.

PHP 8 str_contrains

The str_contains function in PHP 8 is a great welcomed function that easily solves a frequent task by developers in their code. This function can be used to determine if a string is contained in another given string (substring). It works by performing a case-sensitive lookup returning true if a string (needle) is found in the substring (haystack), otherwise, it's false for nothing found. Let's see a few examples of str_contains in action in PHP 8 and above. In the first example, the result is true because '123' is indeed found in 'test 123'. However the second is false because '456' is not present. The third is true as the number 2 is in the haystack string, whereas the final example is false, because the uppercase word 'test' is not in the haystack string, as the word 'test' is in lowercase. This is a common gotcha, that string comparison is case-sensitive. You can also use this function to find out if a string contains numbers because passing a string of characters is a valid function parameter.

# Result: true
str_contains('test 123', '123');

# Result: false
str_contains('test 123', '456');

# Result: true
str_contains('test 123', '2');

# Result: false
str_contains('test 123', 'TEST');

How to perform a string contains case insensitive search in PHP

To use the str_contains function but perform a case-insensitive lookup you have to use another PHP function in order for that to work. The easiest way is to transform the string to all the same case before running the comparison. To convert a string to lowercase with PHP use the strtolower function. This means that then regardless of the case you can properly compare the two strings and get the correct output. The first and second examples both work in this case, but it must be noted that if you do indeed care about the case of the string, don't string to lower the haystack or needle.

# Result: true
str_contains('test 123', strtolower('TEST'));

# Result: true
str_contains(strtolower('test 123'), strtolower('TEST'));

Another thing to watch out for is comparing against an empty string. Because of this, it will always return true. If you pass a variable into this, be careful if the variable is never set to blank. You could wrap the str_contains function in an "if statement" to first check if the string is not empty.

# Result: true
$nothing = '';
str_contains('test 123', $nothing);

Bare in mind that str_contains only accepts a string variable, therefore booleans or arrays would trigger the following error; "Uncaught TypeError: str_contains(): Argument #2 ($needle) must be of type string, array given". To avoid this error, pass strings and nothing else.

# Result: Fatal Error
str_contains('test 123', []);

String contains PHP 7 and below

In PHP 7 and below (although PHP 7 is now not officially supported), there isn't the beauty of the str_contain and instead, you'll have to use either strpos or strstr. The RFC (request for change) back in 2020, was issued by PHP developers because it was felt that:

  • Using strpos or strstr requires strict comparison ("===" or "!==") to avoid undesired outcomes
  • Isn't intuitive for developers when in code
  • Can be hard to remember to format
  • Common PHP frameworks, therefore, created helper functions to overcome this behavior, but it's a standard and is a per-framework methodology.

In PHP 7 and below you have to wrap strpos (or strstr) in an If statement using a strict comparison against a false boolean return outcome.

if (strpos('test 123', '123') !== false) {
 echo '123 is in the string';
}

# OR

if (strstr('test 123', '123') !== false) {
 echo '123 is in the string';
}

Conclusion

If you are using PHP 8 or above, use the str_contains function to keep your code clean and easier to read. If you're on an older version of PHP, 7 and below, use either strpos or strstr to compare the string against the substring.

  • Use str_contains with PHP 8 and above which is binary-safe
  • Remember str_contains is case sensitive
  • Don't pass anything other than strings to the str_contains function
  • Use strpos or strstr with PHP 7 and below

Senior PHP developer. Author of Dev Lateral guides and tools. The complete place for PHP programmers. Available to hire to help you build or maintain your PHP application.

Looking for industry-leading PHP web development?

API development WordPress Hosting ★ and more 🐘

We use cookies to enhance your browsing experience, and analyse website traffic in accordance with our Privacy and Cookie Policy. Our cookies, including those provided by third parties, collect anonymous information about website usage and may be used for targeted advertising purposes. By clicking "Reject non-essential" you can opt out of non-essential cookies. By clicking "Accept all" you agree to the use of all cookies.


Reject non-essential Accept all