BetaRide
BetaRide

Reputation: 16844

How to get a readable string from binary data in PHP?

I have a string with a few non non-printable bytes. I want to convert this string into a human readable format. Non-printable charachters can be represented with something like ? or <07>, printable charachters should remain untouched.

Is there an easy way to do that in PHP?

Upvotes: 0

Views: 816

Answers (1)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324620

There are many, many ways to do something like this.

My choice would be:

$string = preg_replace_callback('/[\x00-\x08\x0B\x0C\x0E-\x1F]/',function($char) {
    // format as desired, for instance:
    return "{".dechex(ord($char[0]))."}";
},$string);

You can define "non-printable" how you want, the one I did there is basically "Everything before Space, but allow Tab, CR and LF".

Upvotes: 2

Related Questions