PHP strpos

Summary: in this tutorial, you’ll learn how to use the PHP strpos() function to get the index of the first occurrence of a substring in a string.

Introduction to the PHP strpos() function #

The PHP strpos() function returns the index of the first occurrence of a substring within a string.

Here’s the syntax of the strpos() function:

strpos ( string $haystack , string $needle , int $offset = 0 ) : int|falseCode language: PHP (php)

The strpos() function has the following parameters:

  • The $haystack is a string to search in.
  • The $needle is a string value to search for.
  • The $offset is an integer that represents the index at which the strpos() function starts the search. The $offset defaults to 0.

The $offset can be positive or negative. If $offset is positive, the strpos() function starts the search at $offset number of characters to the end of the string.

If the $offset is negative, the strpos() function starts at the $offset number of characters to the beginning of the string.

If the strpos() doesn’t find the $needle in the $haystack, it returns false.

PHP strpos() function examples #

Let’s take some examples of using the strpos() function.

1) Using PHP strpos() function to search for a substring example #

The following example uses the strpos() function to search for the substring 'to' in the string 'To do or not to do':

<?php

$str = 'To do or not to do';
$position = strpos($str, 'do');

echo $position; // 3Code language: PHP (php)

Try it

Output:

3Code language: PHP (php)