PHP to check substring in a string
We are given two strings.We have to check whether the second string is a sub-string of the first string or not using PHP inbuilt function strpos().
Examples:
Input :$s1 = "geeksforgeeks"
$s2 = "for"
Output : True
Explanation : The string "for" is a substring
of the string Matthew so output is true.
Input :$s1 = "practice.geeksforgeeks"
$s2 = "quiz"
Output : False
The problem can be solved by iterating through the given string from 0 index to final length of the string and comparing the query string with the iterations. But in PHP we can also make use of some inbuilt functions to solve this particular problem.
- strpos(): This function finds the position of the first occurrence of a string inside another string.
- strlen() : Returns length of string.
If the index of 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.
<?php // PHP code to check if a string is // substring of other $s1 = "geeksforgeeks"; $s2 = "geeks"; if (strpos($s1, $s2) >= 0 && strpos($s1, $s2) < strlen($s1)) echo("True"); else echo("False"); ?> |
Recommended Posts:
- How to check a string is entirely made up of the same substring in JavaScript ?
- JavaScript | Difference between String.slice and String.substring
- JavaScript | Check if a string is a valid JSON string
- PHP | Program to check a string is a rotation of another string
- How to check if URL contain certain string using PHP?
- How to check if string contains only digits in JavaScript ?
- JavaScript | Check if a variable is a string
- How to check if a string is html or not using JavaScript?
- How to check a string begins with some given characters/pattern ?
- JavaScript | Check if a string is a valid hex color representation
- How to check empty/undefined/null string in JavaScript?
- Difference between substr() and substring() in JavaScript
- How to check the existence of URL in PHP?
- PHP | check if a number is Even or Odd
- PHP | Palindrome Check
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



