Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,955 questions

51,897 answers

573 users

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(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($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 4 hours ago by avibootz

Related questions

...