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:
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:
- start of string / hex string on it's own line
- 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: