Skip to content
Related Articles

Related Articles

PHP to check substring in a string
  • Difficulty Level : Easy
  • Last Updated : 13 Mar, 2018

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.

  1. strpos(): This function finds the position of the first occurrence of a string inside another string.
  2. 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");
?>

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :