PHP to check substring in a string
In this article, we will see how to check the substring in a string. We are given two strings & we have to check whether the second string is a substring of the first string or not using PHP built-in strpos() function. This function is case-sensitive, which means that it treats upper-case and lower-case characters differently.
Example: Consider the below example.
Input :$s1 = "geeksforgeeks" $s2 = "for" Output : True Explanation: The 2nd string "for" is a substring of the 1st string "geeksforgeeks". So, the output is true. Input :$s1 = "practice.geeksforgeeks" $s2 = "quiz" Output : False Explanation: The 2nd string "quiz" is not a substring of the 1st string "practice.geeksforgeeks". So, the output is false.
Approach: The problem can be solved by iterating through the given string from the 0th index to the final length of the string and comparing the query string with the iterations. If the index of the first occurrence of the given string is within the length indices of the given string then the output returns true, else the output returns false.
In PHP, we can also make use of some built-in functions to solve this particular problem. These functions are:
- strpos(): This function finds the position of the first occurrence of a string inside another string.
- strlen() : It will returns length of string.
Example: This example describes the comparison of the 2nd string with the 1st string & accordingly it will return true if the substring is present in it otherwise return false.