简体   繁体   中英

PHP align text vertically with tabulators

This might be very noobish question and I'm sure someone already asked this but I didn't find anything. So my problem is pretty simple. In my php file I have function that saves visitor's IP address along with timestamp into file:

$ip=$_SERVER['REMOTE_ADDR'];
$timestamp=date("\td.m.Y  H:i:s");
$fp = fopen('log', 'a');
fwrite($fp, $ip."  ".$timestamp."\n");
fclose($fp);

I use \\t to put tabulator between IP and timestamp, but IPs are different lenght so it does this:

86.122.146.130          05.08.2017  09:59:25
188.175.16.157          05.08.2017  13:36:42
60.191.38.77    05.08.2017  17:37:44
106.74.48.171   05.08.2017  21:38:57
185.110.132.239         06.08.2017  02:08:04

How can I align timestamps vertically? Thank you.

You can use sprintf() to pad with spaces and align the values:

$line = sprintf("%-20s %20s\n", $ip, $timestamp);

Code above returns a string with two fields of 20-character length, where first field is left-aligned (note the minus sign).

Also you can use str_pad() function (by default it pads a string with spaces from right side):

$line = str_pad($ip, 20) . str_pad($timestamp, 20) . "\n";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM