0

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?

2
  • 3
    Can you explain what is non binary bytes? Commented Dec 11, 2014 at 12:25
  • 1
    A byte is always binary... Please supply us with an example input and output... In the meantime, read up on ord(), chr(), unpack() and bindec() Commented Dec 11, 2014 at 12:28

1 Answer 1

2

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".

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for pointing me into the right direction. I had to replace the double quotes around the pattern to singel quotes. Furhter more the function takes an array not a single character. So I had to change it to function($match) {return "{".dechex(ord($match[0]))."}";} .
@BetaRide I've updated my answer with those edits - sorry for the confusion there :D
well this fixed a problem for me where I could NOT explode a string even if I could see the needle in there, I just returned "" instead . thank you so much

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.