Instead of doing all the str_replace's on the membergroupids, why not explode it to an array, manipulate and implode back again.
Ie. something like:
PHP Code:
// Explode to an array
$mbrgrp_array = explode(",", $membergroupids);
// Add remove/add group to array
....code here...
// Make it a comma seperated string again
$membergroupids = implode(",", $mbrgrp_array);
Just trying to simplify your code first as that makes it easier to troubleshoot.