Thursday, 4 January 2018

strpos() and stripos() function | PHP

Tags

strpos() helps us to find out the first occurrence of a substring in a string. This function returns an integer value of the position of the first occurrence of the string. Both the strpos() and stripos() function servers the same purpose. The main difference between both function is case-sensitivity.

strpos() is case-sensitive but stripos() is not case-sensitive.


strpos(original_str, search_str, start_pos)

Parameters Used:
Two parameters are mandatory for the both functions whether third parameter is optional. 

Parameter 1: This parameter refers to the original string. This parameter is mandatory.
Parameter 2: This parameter refers to the substring, occurrence of which we have to find. This parameter is also mandatory.
Parameter 3: Refers to the position of the string from where you want to search the substring. This string is optional.

Example of strpos():

<?php


function use_of_strpos($original_string,$sub_string){
     
      $position=strpos($original_string,$sub_string);
      return $position;
     
}

//Driver code

$original_string="Guru Tegh Bahadur Institue of technology";
$sub_string="Bahadur";

$result=use_of_strpos($original_string,$sub_string);
if($result){
     
     echo nl2br("\r\n");
     echo ("Substring is present at position: ").$result;
     echo nl2br("\r\n");
}
else{
  
     echo nl2br("\r\n");
     echo nl2br("\r\nSubstring is not present in the original string\r\n");
}

$sub_string="bahadur";
$result=use_of_strpos($original_string,$sub_string);
if($result){
     
     echo nl2br("\r\n");
     echo ("Substring is present at position: ").$result;
     echo nl2br("\r\n");
}
else{
  
     echo nl2br("\r\n");
     echo nl2br("\r\nSubstring is not present in the original string\r\n");
}



?>


OUTPUT:



Example of stripos():

<?php

function use_of_stripos($original_string,$sub_string){
     
      $position=stripos($original_string,$sub_string);
      return $position;
     
}

//Driver code

$original_string="Guru Tegh Bahadur Institue of technology";
$sub_string="bahadur";

$result=use_of_stripos($original_string,$sub_string);
if($result){
     
     echo nl2br("\r\n");
     echo ("Substring is present at position: ").$result;
     echo nl2br("\r\n");
}
else{
  
     echo nl2br("\r\n");
     echo nl2br("\r\nSubstring is not present in the original string\r\n");
}


?>


OUTPUT:





EmoticonEmoticon