PHP: Check if a string contains a substring.

In this PHP tutorial, we will show you how to check if a string contains a given substring.

In other words, does the string contain a certain word or a set of characters?

A case insensitive check using the stristr function.

If you want your check to be case insensitive, then you can use PHP’s stristr function like so:

//Our example string.
$string = 'This is a sentence.';

//The substring we are looking for.
$substring = 'this';

//Use stristr to check if the substring
//is present in our string.
if(stristr($string, $substring)){
    echo 'Our string contains: ' . $substring;
}

In the PHP code above, we were able to confirm that our string contains the substring “this”.

As you can see, the stristr function takes in two parameters:

  1. $haystack: This is the string that we want to check for our substring. In the code snippet above, we passed in the variable $string as our haystack.
  2. $needle: This is the substring that we are searching for.

It is important to note that the stristri function does not actually return a TRUE value if the substring is found. Instead, by default, it will return the segment of the string that starts with the $needle we were looking for.

For example:

$string = 'we are currently in 2020';
$needle = 'currently';
var_dump(stristr($string, $needle));

If you run the code above, you will see that stristr returns the string “currently in 2020”. This is due to the fact that this is where our $needle begins.

However, if stristri cannot find the substring in question, then it will return a boolean FALSE value.

$string = 'just another random sentence';
$substring = 'doesnt exist';
var_dump(stristr($string, $substring));

In this case, the function will return a FALSE value.

A case-sensitive check to see if a string contains a substring.

If the case does matter to you, then you can use the strstr function instead.

Note that these two functions look extremely similar. However, in this case, the function is missing the “i” in the middle.

The strstr function works the exact same way as stristr, except for the fact that it is case-sensitive:

//Our string.
$string = 'Hi. I am John.';

//The substring we are looking for.
$needle = 'john';

//Check if it exists inside our string.
if(strstr($string, $needle)){
    echo 'Substring was found!';
} else{
    echo 'Substring was NOT found!';
}

If you run the code above, you will see that it prints out the following output:

Substring was NOT found!

This is because we searched for “john” with a lowercase J, whereas the string in our $haystack actually starts with an uppercase J.

If you modify the $needle variable and use an uppercase J instead, then our code will find the substring in question.