下载时PHP / Curl进度

I'm using a system curl command via php to download a file. That is all working fine, but I'm now trying to show some progress as it's downloaded.

The curl command and php called is:

$a = popen("cd user; curl -O -# remote.server.com/filename.tar.gz 2>&1", 'r');

ob_flush();flush();
while($b = fgets($a, 64)) {
    ob_flush();flush();
        if (preg_match('~\b(error|fail|unknown)\b~i',$b)) {
            echo "error^$b";
            exit;
        }
        echo str_replace('#','',$b);
       ob_flush();flush();
}
pclose($a);

This is called using ajax and the output is displayed in a div:

var last_response_len = false;
        $.ajax(url, {
            xhrFields: {
                onprogress: function(e)
                {
                    var this_response, response = e.currentTarget.response;
                    if(last_response_len === false)
                    {
                        this_response = response;
                        last_response_len = response.length;
                    }
                    else
                    {
                        this_response = response.substring(last_response_len);
                        last_response_len = response.length;
                    }
                    $(upg).show();
                    console.log(this_response)
                    var count = this_response.match(/%/g);
                    if (count !== null && count.length != 2) $(msg).html(this_response);
               }
            }
        })

This works but the results showin in the msg div are not consistent. I may get :

1%
5%
12.1%
12.5% 13.2%
14.2%
5.3%
16.7%

I get partial results ie: 5.3% instead of 15.3%, I get multiple results within the same output ie: 12.5% & 13.2%

is there anyway to standardise this so I only get 0% through to 100% ?

Thanks

change the php str_replace to

str_replace(['#', ' '], '', $b);

Then you get only the percentage, without the preceding blanks, which you can just insert to the container without editing.

Example: https://3v4l.org/OGWqU