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
$haystackis a string to search in. - The
$needleis a string value to search for. - The
$offsetis an integer that represents the index at which thestrpos()function starts the search. The$offsetdefaults 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)Output:
3Code language: PHP (php)