English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

PHP Basic Tutorial

PHP Advanced Tutorial

PHP & MySQL

PHP Reference Manual

PHP strpos() Function Usage and Example

   PHP String String Functions Manual

    The strpos() function is used to find the first occurrence of a string within another string (case-sensitive).

Syntax

strpos(string,find,start)

Definition and Usage

The strpos() function is used to find the first occurrence of a string within another string (case-sensitive).

Note:The strpos() function is case-sensitive.

Note:This function is binary safe.

Related Functions:

  • strrpos() - Find the last occurrence of the search string in another string (case-sensitive)

  • stripos() - Find the first occurrence of the search string in another string (case-insensitive)

  • strripos() -Find the last occurrence of the search string in another string (case-insensitive)

Return Value

It returns the position of the first occurrence of a string in another string, or false if the string is not found

Parameter

NumberParameters and Description
1

string

Required. It specifies the string to be searched

2

find

Required. It specifies the string to be searched for

3

start

It specifies the position to start the search.

If this parameter is not provided, the search will start counting from the character number of the string. If it is negative, the search will start from the specified number of characters from the end of the string

Online Example

Try the following example, find the first occurrence of 'php' in the string:

<?php
    //Example1, find the first occurrence of 'php' in the string
    echo strpos("www.oldtoolbag.com php basic tutorial!"php");
    echo '<br>';
    //Example2, find the first occurrence of 'php' in the string
    echo strpos("php basic tutorial www.oldtoolbag.com!"php");
    echo '<br>';
    //Example3
    $mystring = 'abc';
    $findme = 'a';
    $pos = strpos($mystring, $findme);
    // Note that here we are using '==='. The simple '==' does not work as we expect.
    // Because 'a' is the character at the 0th position (the first character).
    if ($pos === false) {
        echo "Cannot find the string '$mystring' in the string '$mystring' ";
    } else {
        echo "Find the string '$findme' in the string '$mystring' ";
        echo "and exists at position $pos";
    }
    echo '<br>';
    ////Example4, ignore the characters before the offset position for the search
    $newstring = 'abcdef abcdef';
    $pos = strpos($newstring, 'a', 1); // $pos = 7, not 0 
    echo $pos;
?>
Test and see‹/›

Output Result

14
0
Find the string 'a' in the string 'abc' and check if it exists at position 0
7

PHP String String Functions Manual