How to Use the PHP strpos() Function

09/07/2021

Contents

In this article, you will learn how to use the PHP strpos() function.

PHP strpos() Function

The strpos() function in PHP is used to search for the first occurrence of a substring within a string. The function returns the position of the substring, or FALSE if the substring is not found.

Syntax:
strpos($string, $substring, $start);
Parameters:
  • $string: The string to search in.
  • $substring: The substring to search for.
  • $start(optional): The position in the string to start searching from. If not specified, the search starts from the beginning of the string.
Example:
<?php
  $string = "Hello World";
  $substring = "Hello";
  $position = strpos($string, $substring);

  if ($position !== false) {
    echo "The substring was found at position $position";
  } else {
    echo "The substring was not found";
  }
?>
Output:
The substring was found at position 0

The strpos() function is case-sensitive, so “hello” is not the same as “Hello”. If you need to perform a case-insensitive search, you can use the stripos() function instead.

It’s important to note that strpos() returns the position of the first character of the substring, not the length of the substring. The position is zero-based, meaning the first character in the string is at position 0.