Register Login

strpos() Function in PHP

Updated Jan 08, 2020

PHP strpos() function

The strpos() function in php is used to find the first occurrence of a substring in a string. it returns numerical value of the position of the first occurrence of the string

Note: strpos() is a case sensitive function, it treats the lower case and upper case characters differently.

PHP Version

4 and above

Syntax

strpos($parentString,$childString,offset)

Parameter

Parameter Type Description
$parentString (mandatory) string  The string from which search performed
$childString (mandatory) string The string needed to found
$offset (optional) integer

it specifies the count of character from where to begin the search. If the offset value is negative, the search will start from the character counted from the end of the string.

Note: PHP added support for negative offset valued to its 7.1.0 version.

Return Value

Returns numerical value of the position of the first occurrence of the string or else return false if string not found.

Note: String position starts from 0, not 1.

Examples

1) PHP strpos() Function Basic Program 

#Program to illustrate strpos function of PHP

$parentString = "Welcome to the Stechies.Stechies is on of the most trusted online tutorial website.";
$childString = "Stechies";
echo "Position of Stechies in the Parent String is : ". strpos($parentString,$childString);

Output

Position of Stechies in the Parent String is: 15

2) PHP strpos() Function with Offset Value

#Program to illustrate strpos function of PHP

$parentString = "Stechies welcomes you.Stechies is on of the most trusted online tutorial website.";
$childString = "Stechies";
echo "Position of Stechies in the Parent String is : ". strpos($parentString,$childString,1);

OUTPUT:

Position of Stechies in the Parent String is: 22

3) PHP strpos()  with Custom Function

#Program to illustrate strpos function of PHP

#Using custom function

function getPosition($parentString, $childString){
    $subStringPosition = strpos($parentString, $childString);
    
    if($subStringPosition === false){
        return "The string ". $childString ." was not found in the string ".$parentString;
    }else{
        return "The string '".$childString."' was found in the string '".$parentString. "' at ".$subStringPosition. " position";
    }
}

$mainString = "Welcome to the Stechies. Stechies is one of the most trusted online tutorial website.";
$subString = "Stechies";

echo getPosition($mainString, $subString);

Output: 

The string 'Stechies' was found in the string 'Welcome to the Stechies. Stechies is one of the most trusted online tutorial website.' at 15 position

 


×