How to unchunk data received through PHP sockets

When using the PHP socket functions to pull data from another website, you'll often find yourself dealing with chunked data. Chunked data often looks like this:

this line is 30 characters lon
g, while this line is 44 characters long.
d this line is 33 characters long

As you can see, each chunk is preceded by a hex string. This hex string corresponds to the string length of the following chunk. Line breaks are included in the chunk, as you can see in the second chunk. So to unchunk the string, you have to find every hex string that is preceded by, and followed by, a line break (or start of end of string), and if the following block of code is equal in length to the hex value, strip out the hex value.

I accomplished this with a regular expression andpreg_replace_callback. In essence, it finds each block of code that follows this pattern:

  1. start of string / hex string on it's own line
  2. anything
  3. hex string on it's own line / end of string

Once it has found all of those patterns, it replaces only the ones where the hex value of #1 is equal to the string length of #2.

My unchunk function:


function unchunk($result) {
    return preg_replace_callback(
            'return hexdec($matches[1]) == strlen($matches[2]) ?
                 $matches[2] :