strpos() : Position of first occurence of the search string

$int_position=strpos(Main_string, Search_string,[optional: offset =0 ]);
Main_string : The string inside of which the search_string will be searched.
search_strig : This is searched within the Main_string.
offset : (optional, integer ) Starting point of search but position count is returned from beginning or ending of the string. Negative integer is allowed to search from end of the string in PHP version 7.0.1
$position=strpos("Welcome",'e');
echo $position; // Output is 1
strpos() Position of search string

Using Offset

Note that first position is 0 ( zero ) .
Position is returned starting from beginning of the string or from ending of the string (negative offset is added in PHP version 7.0.1). This counting of position is irrespective of given offset.
$position=strpos("Welcome",'e',2);
echo $position; // Output is 6 , not 1 
strpos() Position of search string with offset

Checking return value

We may get Boolean value as false and it may also return non-Boolean value. We need to evaluate the return value using === operator or !== to get the correct output. Check this code below and the outputs
$position=strpos("Welcome",'z'); 
if($position==false){
echo " Not found ";	
}else{
echo " Found and postion = ".$position;	
}
// Output is Not found
Using the same code we will search for string W
$position=strpos("Welcome",'W'); 
if($position==false){
echo " Not found ";	
}else{
echo " Found and postion = ".$position;	
}
// Output is Not found
The search string is already present at position 0 . Above code need to change like this to get correct output.
$position=strpos("Welcome",'W'); 
if($position===false){
echo " Not found ";	
}else{
echo " Found and postion = ".$position;	
} // Output is Found and postion = 0
Use === or !== to test the return value

case-sensitive

strpos() is case sensitive
$position=strpos("Welcome",'M'); 
if($position===false){
echo " Not found ";	
}else{
echo " Found and postion = ".$position;	
} // Output is Not Found
  • stripos() case-insensitive search returns position of first occurence
  • strrpos() case-sensitive search returns position of last occurence
  • strripos() case-insensitive search returns position of last occurence


plus2net.com




PHP String Functions

Post your comments , suggestion , error , requirements etc here .




We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
©2000-2020 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer