$pattern = '@(#begin config username\s)(.*?)(\s#end config username)@si';
$replacement = '$1new stuff inside.$3';
$data = file_get_contents('config.txt');
$data = preg_replace($pattern, $replacement, $data);
Of course, if you wanted this to be more generic, you could adapt this into a function with arguments:
function update_config($source, $username, $data) {
$pattern = "@(#begin config $username\\s)(.*?)(\\s#end config $username)@si";
$replacement = "$1$data$3";
return preg_replace($pattern, $replacement, $source);
}
Where $source is the original config file data.