find the kth index of a substring in a string in php

To find the kth index of a substring in a string in PHP, we can use the strpos function. This function returns the first occurrence of a substring in a string, and taking the optional third parameter of the function, we can find the kth index of that occurrence.

Here's an example:

main.php
$string = "This is a sample string";
$substring = "sample";
$k = 1; // the first occurrence

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

for ($i = 1; $i < $k; $i++) {
    $index = strpos($string, $substring, $index + 1);
}

echo $index; // the kth index of the substring in the string
317 chars
12 lines

In this example, we first find the index of the first occurrence of the substring using the strpos function. Then we loop from 1 to k-1 (since we already have the index of the first occurrence), and in each iteration, we find the next occurrence of the substring using strpos with the third parameter set to the index of the previous occurrence plus 1. Finally, we have the kth index of the substring in the variable $index.

gistlibby LogSnag