OneBite.Dev - Coding blog in a bite size

Find The Index Of A Substring Within A String In PHP

Code snippet for how to Find The Index Of A Substring Within A String In PHP with sample and detail explanation

PHP is a scripting language that provides several functions for string manipulation. One such function is finding the index of a substring within a string. This article aims at showing how this can be easily achieved.

Code snippet for finding the index of a substring within a string in PHP

<?php 
   $string = 'Hello, World!';
   $substring = 'World';
   $index = strpos($string, $substring);

   if($index === false) {
       echo 'The substring does not exist in the string.';
   } else {
       echo 'The index of the substring in the string is: ' . $index;
   }
?>

Code Explanation for finding the index of a substring within a string in PHP

Firstly, we define our string and the substring we are seeking within that string. In this case, our string is ‘Hello, World!’, while our substring is ‘World’.

   $string = 'Hello, World!';
   $substring = 'World';

Next, we use the PHP function strpos() to seek out the substring within the main string. This function returns the index where the substring starts in the string. If the substring cannot be found, it returns false.

   $index = strpos($string, $substring);

Subsequently, we evaluate the value returned by the ‘strpos()’ function call using an if statement. In PHP, the strict comparison operator ’===’ does not only check if the two operands are equal, it also ensures that they are of the same data type.

   if($index === false) {
       echo 'The substring does not exist in the string.';
   } else {
       echo 'The index of the substring in the string is: ' . $index;
   }

In this code snippet, if strpos() returns false (meaning that the substring was not found), we display an appropriate message. However, if it returns an integer (the index where the substring begins), we display a different message showing the index. ‘Echo’ is a language construct in PHP used to output one or more strings.

That’s it! Now you know how to find the index of a substring within a string in PHP.

php