How to check if string contains substring in PHP
Abstract: 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 subst
A String is a sequence of characters, which is used either as a literal constant or as some kind of variable. A specific part of a string is known as substring.
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」.
<?php $str = 'This is Main String'; if (strpos($str, 'This') !== false) { echo 'true'; } ?>1234567<?php$str = 'This is Main String'; if (strpos($str, 'This') !== false) { echo 'true';}?>Output: trueExample 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.
<?php $str = 'This is Main String'; $substr = "Hello"; if (strpos($str, $substr) !== false) { echo 'true'; } ?>12345678<?php$str = 'This is Main String';$substr = "Hello"; if (strpos($str, $substr) !== false) { echo 'true';}?>Output: noneExample 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.
<?php $str = 'This is Main String'; if (strpos($str, 'This') === 0 ) { echo 'true'; } ?>1234567<?php$str = 'This is Main String'; if (strpos($str, 'This') === 0 ) { echo 'true';}?>Output: trueConclusion
In this tutorial, you have learned to check if a string contains a substring using PHP programming language.