This article demonstrates how to check if a substring occurs within a string in PHP.

1. Using strpos() function

The strpos() function returns the index of the first occurrence of a substring in a string, and false if the substring is not found. To check if a substring is found in a string or not, you can test the return value of strpos() using the !== operator.

 
The following example demonstrates its usage. Take note of the !== operator. You cannot use the equality operator (!=) or the negation operator (!) here. The strpos() function returns 0 if the substring is found at the beginning of the string, and both 0 != false and !0 evaluate to false, and 0 !== false evaluates to true.

Download  Run Code

 
You may want to create a utility function that accepts two arguments, $haystack and $needle, and returns true if $needle is a substring of $haystack; false otherwise.

Download  Run Code

 
To make the search case-insensitive, use the stripos() method. It is similar to strpos(), but is case-insensitive.

Download  Run Code

2. Using strstr() function

Another option is to use the strstr() function to determine if a particular substring occurs within a string. It returns the portion of the string starting from the substring’s first occurrence till its end, or false if the substring is not found.

Download  Run Code

 
Note that strpos() is faster and less memory-intensive than the strstr() function. Also note that the search performed by the strstr() function is case-sensitive. For a case-insensitive search, you can use the stristr() method.

Download  Run Code

3. Using preg_match() function

Finally, you can use the preg_match() function to perform a regular expression match that checks if a substring occurs within a string. It returns 1 in the case of a match, and 0 in the case of no match.

 
The following code demonstrates its usage. On failure, the preg_match() function can return false (or a value that evaluates to false). Therefore, you should always use the === operator for checking the return value of this function.

Download  Run Code

 
Note that preg_match() is overkill for such a trivial task. It uses regular expressions, which causes it to perform slower than the strpos() and strstr() functions. For a case-insensitive search, you can place i at the end of a regular expression.

Download  Run Code

4. Using substr_count() function

As a bonus, here’s another approach to checking if a substring occurs within a string. It uses the substr_count() function, which counts the number of times the substring occurs in the string. If that count is greater than 0, then we can say that the substring occurs within a string.

Download  Run Code

 
Note that the search is case-sensitive. To make the search case-insensitive, you can convert the string and the substring to the same case (both uppercase or both lowercase).

Download  Run Code

That’s all about determining if a substring occurs within a string in PHP.