Find the Position of the First Occurrence of a Substring in a String in PHP With Example

Hello Friends Today, through this tutorial, I will tell you How do you find the position of the first occurrence of a substring within a string using PHP, PHP 8, PHP 8.1, PHP 8.2, PHP 8.3 With Example. In PHP, you can find the position of the first occurrence of a substring within a string using the `strpos()` function. Here’s how you can use it:

<?php

// Original string
$string = "The quick brown fox jumps over the lazy dog.";

// Substring to find
$substring = "brown";

// Find the position of the first occurrence of the substring
$position = strpos($string, $substring);

if ($position !== false) {
echo "The substring '$substring' was found at position: $position";
} else {
echo "The substring '$substring' was not found in the string.";
}

?>

In this example, the `strpos()` function takes two parameters:

1. The original string.
2. The substring to find.

It returns the position (index) of the first occurrence of the substring within the string, or `false` if the substring is not found.

Keep in mind that `strpos()` returns `0` if the substring is found at the beginning of the string. Therefore, it’s important to use `!== false` for comparison to avoid incorrect results, as `0` evaluates to `false` in PHP when using loose comparison.

If you want to find the position of the last occurrence of a substring within a string, you can use the `strrpos()` function instead.