strpos() and stripos() functions in PHP

strpos() and stripos() functions in PHP

PHP strpos() and stripos() capacities: In this article, we will find out about PHP capacities strpos() and stripos() with examples.

These capacities are utilized to discover the situation of any substring in the string. Here, strpos() is case-delicate, while strpos() isn’t case touchy.

PHP – strpos() work

This capacity is utilized to locate the primary event of any substring in a string. This capacity restores an integer value which is the beginning record of the first event of the given substring.

Note: strpos() is case touchy.

Syntax:

strpos(string, substring, [intial_pos]);

Here,

  1. string – is the first string, for example, the source string in which we need to look through the substring.
  2. substring – is the string which is to be looked in the string.
  3. [initial_pos] – it is a discretionary parameter, which might be utilized to characterize the beginning situation, from where you need to look through the substring.

Return type: the capacity strpos() restores an integer value which will be a list of the substring in the string.

PHP code

<?php
   //function to find substring in string
   //parameters
   //$sub_str - string to be searched
   //$str - main string in which we have to 
   //find the substring
   
   function searchSubstring($sub_str, $str){
       //calling function, here third parameter is 
       //an optional - we are specifying 0 that means
       //search should start from 0th index
       $pos = strpos($str, $sub_str, 0);
       return $pos;
   }
   
   //main code to test given function
   //to find substring in the string
   $main_string = "Hello world, how are you?";
   $sub_string = "how";
   
   //position will store in $index
   $index = searchSubString($sub_string, $main_string);
   
   if($index == null){
       echo $sub_string." does not exists in the string";
   }
   else{
       echo $sub_string." found at ".$index. " position";
   }
?>

Output:

how found at 13 position

PHP-stripos() work

This capacity is the same as strpos(), all activities are the same aside from the case, this capacity doesn’t check case-affectability. stripos() disregards the case while finding any substring in the string.

Example: Refer above code and search “HOW”

Reference: https://www.w3schools.com/php/func_string_strpos.asp

Recent Posts

error: Alert: Content is protected!!