Find the Position of a Substring in a String with the strpos() Function in PHP

30-01-2023
PHP

Learn how to use the strpos() function in PHP to find the position of a substring in a string. See examples and sample code to help you use this function in your PHP projects. Whether you need to check if a string contains a certain word or just want to find the index of a character, strpos() is the perfect tool to get the job done.

strpos is a function in PHP that returns the position of the first occurrence of a substring within a string. If the substring is not found, strpos returns false.

Example 1:


<?php 
$text = "Hello World"; 
$search = "World"; 
$position = strpos($text, $search); 
if ($position !== false) { 
  echo "The string '$search' was found in the string '$text' at position $position"; 
} else { 
  echo "The string '$search' was not found in the string '$text'"; 
}
?>

Output:

The string 'World' was found in the string 'Hello World' at position 6

Example 2:


<?php 
$text = "Welcome to PHP"; 
$search = "JAVA"; 
$position = strpos($text, $search); 
if ($position !== false) { 
  echo "The string '$search' was found in the string '$text' at position $position"; 
} else { 
  echo "The string '$search' was not found in the string '$text'"; 
}
?>

Output:

The string 'JAVA' was not found in the string 'Welcome to PHP'