Parth Vora Parth Vora - 1 month ago 5
PHP Question

String search from the end with skipping matches in PHP

I want to find the position of a sub string in a string from the end, but with skip parameter. So if I pass 3 it should skip first 3 matches and return the position of the 4th match if found (or

false
if no match is found.

For example:

$str = '<h1>First</h1><h1>Second</h1><h1>Third</h1><h1>Fourth</h1>';

echo custom_search($str, '<h1>', 2);


should return 14.

Search will start from the end of the string and will skip the first 2 found matches for
<h1>
and will return the position of the next matching
<h1>
(the position is relative to the start of the string).

Answer

As @RomanHocke said in his comment, you have to use strrpos in a loop, updating the offset parameter at each iteration.

Something like this (it works, although it could certainly be improved) :

$str = '<h1>First</h1><h1>Second</h1><h1>Third</h1><h1>Fourth</h1>';

var_dump(custom_search($str, '<h1>', 0)); // int(43)
var_dump(custom_search($str, '<h1>', 1)); // int(29)
var_dump(custom_search($str, '<h1>', 2)); // int(14)
var_dump(custom_search($str, '<h1>', 3)); // int(0)
var_dump(custom_search($str, '<h1>', 4)); // bool(false)
var_dump(custom_search($str, 'I am not in the string', 0)); // bool(false)

function custom_search ($str, $substr, $n = 0) {
    $offset = 0;
    $total_offset = 0;
    for ($i=0; $i<=$n; $i++) {
        $strrpos = strrpos($str, $substr, $offset);
        $str= substr($str, 0, $strrpos);
    }
    return $strrpos;
}
Comments