PHP: is there a way to see "invisible" characters like \n-ThrowExceptions

Exception or error:

Is there a way to see invisible characters like whitespace, newlines, and other non-printing characters in a manner like print_r() ?

Reason is there is some sort of character in my array that I can’t see and breaking things.

Object Object
(
  [name] => name
  [numbers] => Array
      (
          [0] => 123

          [1] => 456
          [2] => 789
      )
   [action] => nothing
)

See the weird whitespace between [0] and [1]? When printing out [0] a newline gets printed as well. But no where do I assign a newline to [0] so I’m quite confused.

Is there a built in function in php that’s like show_invisible(Object->numbers[0]) and it will show 123\n or similar?

How to solve:

You can use the addcslashes function:

string addcslashes ( string $str, string $charlist )

which will return a string with backslashes before characters. An example would be:

<?php
echo addcslashes('foo[ ]', 'A..z');
// output:  \f\o\o\[ \]
// All upper and lower-case letters will be escaped
// ... but so will the [\]^_`
?>

Answer:

To see all the invisible characters not only \r, \n etc… It’s good to see json_encodeed version and everything is clear:

$str = "...";
echo json_encode($str);

Answer:

You could probably list all the control characters out, but try this for a quick fix ?

PHP – print string with control characters

It’s a simple str_replace("\n",'\n',$string) kind of fix, but you could probably adapt the solution for a function callback on the array to convert those characters.

Answer:

You could just run your php script, and pipe it straight to hexdump -C

Answer:

To have an exact replication of the input string, without the surrounding " and without serialization, use this wrapper for json_encode():

substr(json_encode((string)$string), 1, -1)

It does a string casting and removes the " of the JSON standard.

Leave a Reply

Your email address will not be published. Required fields are marked *