Reputation:
I have a php variable which contains data from an IO stream (say, a file I've just read). This string contains a number of special characters such as \n and \t and so forth. I need to be able to print all of these characters to screen so that I can examine the string visually. I'm presuming there's some way of escaping them, but for the life of me I can't figure out how.
Upvotes: 5
Views: 1396
Reputation: 2156
I think this is a very old question but none of the answers are very helpful. We use this function for examining strings like this, so hopefully it can help someone else out:
function convert_non_visual_ascii_chars_to_representation($string) {
$non_vis_chars = [
0 => 'NUL',
1 => 'SOH',
2 => 'STX',
3 => 'ETX',
4 => 'EOT',
5 => 'ENQ',
6 => 'ACK',
7 => 'BEL',
8 => 'BS',
9 => 'TAB',
10 => 'LF',
11 => 'VT',
12 => 'FF',
13 => 'CR',
14 => 'SO',
15 => 'SI',
16 => 'DLE',
17 => 'DC1',
18 => 'DC2',
19 => 'DC3',
20 => 'DC4',
21 => 'NAK',
22 => 'SYN',
23 => 'ETB',
24 => 'CAN',
25 => 'EM',
26 => 'SUB',
27 => 'ESC',
28 => 'FS',
29 => 'GS',
30 => 'RS',
31 => 'US',
];
// Convert the string
$new_string = '';
$length = strlen($string);
for ($i = 0; $i < $length; $i++) {
$char_code = ord($string[$i]);
if (isset($non_vis_chars[$char_code])) {
$new_string = $new_string . '[' . $non_vis_chars[$char_code] . '/' . $char_code . ']';
} else {
$new_string = $new_string . $string[$i];
}
}
return $new_string;
}
Upvotes: 0
Reputation: 5478
Well interesting question. I haven't been able to find anything in Google about escaping newline char.
I guess you could try using nl2br, which would convert your newlines to <br />
, but that isn't quite useful, since you won't know when you have an actual break tag or newline char.
So, to get past this, you I recommend two options. If you only want to examine the string, use var_dump() or var_export()
The following code gives gives the output 'text \\n'
:
$var = 'text \n';
var_export($var);
Or, if you want to work further with it, you can use a piece of code like that, but let's be honest, this is quite messy...
$var = 'text \n';
$search = array('\n', '\r', '\r\n');
$replace = array('[n]', '[r]', '[r][n]');
echo str_replace($search, $replace, $var);
This would output text [n]
Upvotes: 0