PHP Strings
Generating Fixed-Width Field Data Records
Problem
You need to format data records such that each field takes up a set amount of characters.Solution
Example Generating fixed-width field data records$books = array( array('Elmer Gantry', 'Sinclair Lewis', 1927),
array('The Scarlatti Inheritance','Robert Ludlum', 1971),
array('The Parsifal Mosaic','William Styron', 1979) );
foreach ($books as $book) {
print pack('A25A15A4', $book[0], $book[1], $book[2]) . "\n";
}
Discussion
The format string A25A14A4 tells pack() to transform its subsequent arguments into a 25-character space-padded string, a 14-character space-padded string, and a 4-character space-padded string. For space-padded fields in fixed-width records, pack() provides a concise solution.To pad fields with something other than a space, however, use substr() to ensure that the field values aren’t too long and str_pad() to ensure that the field values aren’t too short.
Example Generating fixed-width field data records without pack( )
$books = array( array('Elmer Gantry', 'Sinclair Lewis', 1927),array('The Scarlatti Inheritance','Robert Ludlum', 1971),
array('The Parsifal Mosaic','William Styron', 1979) );
foreach ($books as $book) {
$title = str_pad(substr($book[0], 0, 25), 25, '.');
$author = str_pad(substr($book[1], 0, 15), 15, '.');
$year = str_pad(substr($book[2], 0, 4), 4, '.');
print "$title$author$year\n";
}
No comments:
Post a Comment