OneBite.Dev - Coding blog in a bite size

Find The Position Of The First Occurrence Of A Substring In A String In PHP

Code snippet for how to Find The Position Of The First Occurrence Of A Substring In A String In PHP with sample and detail explanation

Finding the position of the first occurrence of a substring within another string is a common task in programming. In PHP, this operation can easily be accomplished with built-in functions.

Code snippet: Using the strpos() Function

Below is a simple PHP code snippet using the strpos function to find the first occurrence of a substring in a string:

$string = 'Hello, World!';
$substring = 'World';
$position = strpos($string, $substring);
if ($position !== false) {
    echo "The position of $substring in $string is: $position";
} else {
    echo "$substring is not in $string";
}

Code Explanation: Using the strpos() Function

The PHP strpos function can help you discover the position of the first occurrence of a specific substring within another string. Let’s break down how this function operates using the code snippet above as a reference.

First, we define the main string and substring:

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

The variable $string contains our original, main string, and $substring is the string we want to find in $string.

Next, we invoke the strpos function:

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

The strpos function requires at least two parameters—the main string and the substring. The function then returns the position where the substring starts in the main string. It is important to note that, as per PHP’s indexing, the starting position is 0, not 1. If the substring is not in the main string, the function will return false.

Afterward, we use an if statement:

if ($position !== false) {
    echo "The position of $substring in $string is: $position";
} else {
    echo "$substring is not in $string";
}

This statement verifies whether a valid position is returned, then outputs the position. If the substring is not found, we output a relevant message.

In summary, strpos is an efficient, built-in PHP function for finding the first occurrence of a substring within a string.

php