PHP string functions – strpos

In this tutorial you will learn how to use the strpos function to find occurrences of a string within another string and then return the position (index) of an occurrence of that string. For example, you could find a specific word in a sentence and then where that word is located in the sentence.

You can also specify an optional offset parameter which specifies where you want to start searching from within the string you are searching. Watch the video below and then scroll down to see the sample PHP code for the strpos function.

Sample PHP code:

1
2
3
4
5
6
7
8
9
10
<?php
 $string = "The quick brown fox jumps over the lazy dog.";
 $word = "fox";
 // strpos(string you want to look in, string you want to find, offset - where you
 // want to start looking from, optional, can be used if multiple occurences
 // of the target string in the string you are searching)
 // eg. strpos("string", "word", 4) where 4 is the offset.
 
 echo strpos($string,$word);
?>

PHP Manual references: