1.1K

The PHP strpos function is used to find a substring in a given string. It returns the numeric value of the first occurrence of the specified substring.

Syntax for using strpos

The PHP strpos function is used as follows:

$position = strpos($given_string, $search_string);

Note: When searching using the strpos function, case is sensitive. So searching for the keywords “Test” and “test” will give different results.

Position counting starts from 0, not 1.

Using demo versions, I will demonstrate the use of this function to search for a given substring and a user-entered value.

A simple example of using the strpos function

Check out the following example, where I used lookup values ​​to demonstrate how the PHP strpos function works:


View online demo and code

PHP code:

"; echo " The given substr found at: $position"; ) ?>

strpos PHP example:

The string contains the search term: ‘strpos’! The given substring found at: 10

Example of using strpos to search for a user-entered term

This method may be useful in certain scenarios. For example, when a form does not allow certain words to be entered.

In addition, you can check whether the word specified by the user for search is contained in the source string. Based on this, you can output certain results in the form of an answer.

In this demo, the user can enter a term into a text field. Once the button is clicked, the strpos function is run to check if the original string contains a substring. The following message will be displayed on the screen:


For the demo I used the following source line:

$source_string = "In this demo, I am using a user entered search term to check if string contains search term or not by using strpos!";

Try entering different letters or words to search to see if the function returns false . Also, try entering terms in capital or small letters to see the difference.

The following PHP strpos utf 8 example was used for this:

"; if ($posistion === false) ( echo "The source string does not contain the: "$search_term"!"; ) else ( echo "The string contains the search term: "$search_term"!
"; echo " The given substring found at: $position"; ) echo "