The PHP provides strpos() function to check if a string contains a specific substring or not. The strpos() function returns the position of the first occurrence of a substring in a string. If substring not found, it return false as output. This tutorial provides you three examples to check if a string contains a substring or not. Also you can check if the substring is at start of main string.

Example 1.

The following code will evaluate to true because the main string $str contains the substring ‘This‘ in it. This will print “true”.

Example 2.

The following code will evaluate to false because the main string $str doesn’t contains the substring ‘Hello‘ in it. This will nothing print.

Example 3.

The following code will check if a String contains a substring at start. The following code will evaluate to true because the main string $str contains the substring ‘This‘ at start.

Conclusion

In this tutorial, you have learned to check if a string contains a substring using PHP programming language.