Techniques for Managing Text Truncation
Learn and practice text truncation with the help of examples.
Text truncation is one of the more challenging aspects of working with fixed-width data formats. Since, by definition, our storage format is of a fixed length, any text we attempt to store that exceeds the size of any given field will not fit. Some systems will provide a warning when this is about to occur or even trigger a fatal error to prevent truncating data.
Let’s take a look at the table below, which contains some example data we will work to store in a limited data format:
Example Text Data
Record Number | Text Value |
1 | Lorem ipsum dolor sit amet |
2 | Nam finibus nulla non bibendum bibendum |
3 | Ut sed ante euismod, vulputate justo sit amet |
We will represent this with the following PHP array:
<?php$data = [['record_no' => 1,'text' => 'Lorem ipsum dolor sit amet',],['record_no' => 2,'text' => 'Nam finibus nulla non bibendum bibendum',],['record_no' => 3,'text' => 'Ut sed ante euismod, vulputate justo sit amet',]];
Throwing exceptions on data truncation
As we’ve done before, we are going to work to store our data array in a fixed-width data format. We will say that our record numbers will be stored using three characters, and our text data will be stored with up to 10 characters:
<?php$dataString = collect($data)->map(function ($record) {$textValue = str($record['text']);if ($textValue->length() > 10) {throw new Exception('Text value would be truncated.');}return str('')->append(str($record['record_no'])->padLeft(3))->append($textValue->padRight(10));})->join('');
Our code above will currently throw an exception whenever we attempt to store data that exceeds ten characters. This check happens between lines 6 and 8. We can ask ourselves how we might be able to persist our data even if it exceeds the length of an individual record
The exception can be viewed below by clicking the link under the ...