PHP: Check if a string contains a substring.

This is a PHP tutorial on how to check if a string contains a given substring. i.e. 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:

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:

If you run the code above, you will see that stristr returns the string “currently in 2020”. This is because that is where our $needle starts at.

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

In this case, the function will result in a FALSE value.

A case SENSITIVE check to see if a string contains a substring.

If case matters to you, then you can use the strstr function instead. Note that the two functions look extremely similar. However, in this case, the function is missing the “i” in the middle.

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

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 to contain an uppercase J instead, then our code will find the substring in question.

Facebook Comments