Support PHP Version: PHP 7.1, PHP 7.2, PHP 7.3, PHP 7.4, PHP 8.0, PHP 8.1, PHP 8.2, PHP 8.3 With Latest All Version Support.
How to Use `strpos()` function in PHP 8.1 and PHP 8.2 is used to find the position of the first occurrence of a substring within a string. It returns the position of the first occurrence of the substring in the string, or `false` if the substring is not found. Here’s how you can use it with an example:
<?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:
1. We have the original string `”The quick brown fox jumps over the lazy dog.”`.
2. We want to find the position of the substring `”brown”` within this string.
3. We use the `strpos()` function to find the position of the substring.
4. If the substring is found, we print a message indicating the position. If not found, we print a message indicating that the substring was not found.
The output will be:
The substring 'brown' was found at position: 10
This means that the substring `”brown”` was found starting at position 10 in the original string. Remember that in PHP, string positions are zero-based, so the first character of the string is at position 0. If the substring is not found, `strpos()` returns `false`, as in the else condition of our example.