3

Trying to figure out, what PHP is doing with newlines and special characters. I have a string, when I do var_dump($string) the output is:

string 'ls -al

    free -m' (length=16)

How do I view the special characters buried in here? For example need to see if they are \n or&#10 or whatever they are.

Thanks.

Justin
  • 42,716
  • 77
  • 201
  • 296

3 Answers3

6

The best way to see unprintable characters is by printing bin2hex($string). This gives you an actual binary dump of the string. Compare this with your favorite ASCII table or other table specific to the encoding your string is in.

deceze
  • 510,633
  • 85
  • 743
  • 889
  • Ok, so the output of the hex is `6c73202d616c0d0a66726565202d6d` which using a converter from hex to ascii outputs `ls -al??free -m` notice the ??. Those should be \n. Any idea what the heck is going on? – Justin Sep 12 '12 at 07:03
  • 1
    The hex dump looks pretty normal. The `0d0a` in the middle is simply a CRLF Windows linefeed. – deceze Sep 12 '12 at 07:39
2

If you're running your command in an unix environnement with PHP Cli, you may try using cat.

php file.php | cat -e

Else, you can handle var_dump into a string and display manually special chars :

$string = "test
test";

$dump = var_export($string, true);
for ($i = 0; ($i < strlen($dump)); $i++) {
    if ((ord($dump[$i]) < 32) || (ord($dump[$i]) > 127)) {
        echo '(' . ord($dump[$i]) . ')';
    } else {
        echo $dump[$i];
    }
}

// will output 'test(13)(10)test' on Windows, 'test(10)test' on Unix systems.
Alain Tiemblo
  • 36,099
  • 17
  • 121
  • 153
0

You could use:

preg_match("/(&#[0-9]+;)|[\t\r\n]/", $string, $matches);
print_r($matches);
dotoree
  • 2,983
  • 1
  • 24
  • 29