PHP strpos() Function

PHP strpos() is used to find the first position of given character or string inside another string.

In other words, strpos() will find the position of the first occurrence of a string in another string. The returned string positions start at 0, not 1.

Syntax:

strpos(string, find_string, start_position)

Parameters:

The strpos function accepts three parameters. First two string and find_string are mandatory and third start_position is optional.

ParameterDescription
stringRequired. Specifies string in which you want to find something.
find_stringRequired. Specify string or character to find.
start_positionOptional. Set the starting point to begin search.

Usage:

This PHP strpos() function is useful in following scenarios.

  • If you want to break string into multiple part by detecting certain character position such as email by ‘@’ symbol.
  • If you want to make sure that certain word exists at particular position.
  • If you want to check that certain ‘name’ exists in a string containing person names.

Example #1: Find “world” position inside “hello world”

In this example, we have a string “hello world” in which we need to find first occurrence of “world”.

<?php
echo strpos("hello world","world");
?>

Output: This program will return ‘6‘ because counting always started with position ‘0’.

Run example: https://paiza.io/projects/VX-bJATujzs3JPVi7GSGeA


Example #2: Check if string is present (at what position) or not

In this example, we have a string containing fruits name separated by a comma. Therefore, we can pass a comma character as a delimiter to break the string into the array.

<?php
$full_string = 'hello, I am learning PHP. PHP is the most popular language for web development.';
$word_to_find   = 'PHP';
$position = strpos($full_string, $word_to_find);

// If string/word not found, it will return false, else it will return position.
if ($position == false) {
    echo "The string '$word_to_find' found in the sentence '$full_string'";
} else {
    echo "The string '$word_to_find' found in the sentence '$full_string' at position $position";
}
?>

Output:

The string ‘PHP’ found in the sentence ‘hello, I am learning PHP. PHP is the most popular language for web development.’ at position 21.

Run example: https://paiza.io/projects/-5SneX5hyuuVnzvW7CabrQ


Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.