How to remove the last n occurrences of a substring in a string in PHP

1 Answer

0 votes
// Remove last n occurrences of a substring
function remove_last_n_occurrences(string $s, string $sub, int $n): string {
    $positions = [];
    $offset = 0;

    // Find all occurrences
    while (($pos = strpos($s, $sub, $offset)) !== false) {
        $positions[] = $pos;
        $offset = $pos + strlen($sub);
    }

    // Remove from the end
    for ($i = count($positions) - 1; $i >= 0 && $n > 0; $i--, $n--) {
        $start = $positions[$i];
        $s = substr($s, 0, $start) . substr($s, $start + strlen($sub));
    }

    return $s;
}

// Remove extra spaces (collapse multiple spaces, trim ends)
function remove_extra_spaces(string $s): string {
    // Split on any whitespace, remove empty entries, rejoin with single space
    $parts = preg_split('/\s+/', trim($s));
    return implode(' ', $parts);
}

$text = "abc xyz xyz abc xyzabcxyz abc";

$result = remove_last_n_occurrences($text, "xyz", 3);
echo $result . "\n";

$cleaned = remove_extra_spaces($result);
echo $cleaned . "\n";



/*
run:

abc xyz  abc abc abc
abc xyz abc abc abc

*/

 



answered Feb 16 by avibootz
edited Feb 16 by avibootz

Related questions

...