Limiting number of characters displayed in table cell - php

I have a PHP loop that adds data into a table cell. However, I want to apply a static size to the table cell, so if more data is returned than can fit inside the cell I want the excess characters to be cut off and end with a "..."
For example, one data entry has 270 characters, but only the first 100 are displayed in the table cell. Follow by a "..."
Any ideas on how to do this?
Thanks!

if (strlen($str) > 100) $str = substr($str, 0, 100) . "...";

You can use mb_strimwidth
printf('<td>%s</td>', mb_strimwidth($cellContent, 0, 100, '…'));
If you want to truncate with respect to word boundaries, see
Truncate a multibyte String to n chars
You can also control content display with the CSS property text-overflow: ellipsis
http://www.quirksmode.org/css/textoverflow.html
Unfortunately, browser support varies.

function print_dots($message, $length = 100) {
if(strlen($message) >= $length + 3) {
$message = substr($message, 0, $length) . '...';
}
echo $message;
}
print_dots($long_text);

$table_cell_data = ""; // This would hold the data in the cell
$cell_limit = 100; // This would be the limit of characters you wanted
// Check if table cell data is greater than the limit
if(strlen($table_cell_data) > $cell_limit) {
// this is to keep the character limit to 100 instead of 103. OPTIONAL
$sub_string = $cell_limit - 3;
// Take the sub string and append the ...
$table_cell_data = substr($table_cell_data,0,$sub_string)."...";
}
// Testing output
echo $table_cell_data."<br />\n";

Related

Adding spaces in a variable

Good evening
I created a while adding spaces in a variable . it's exactly what I need, but now I need to centralize the text between the spaces:
here is the code in PHP:
$psn = "ABCDEFGH";
$psnSize = strlen($psn);
while($psnSize <= 20)
{
$psn = $psn."&nbsp";
$psnSize++;
}
The max size is 20 characters, and I need all psn's have the same size (20 characters)
I'm getting the result but the spaces are added to the end of the text and now I want to distribute the spaces between the text to get it centralized.
Thank you so much.
You can use all native functions to achieve this:
function createLRPadding($str, $chars = 20)
{
# Count the length
$strlen = strlen($str);
# Don't do anything if you are at the max characters
if($strlen >= $chars)
return $str;
# Get left and right balance
$len = ($chars - $strlen) / 2;
# Create fills on the left and right of the string and implode them to make one string
return implode('', array_fill(0,round($len, 0, PHP_ROUND_HALF_UP),' ')).$str.implode('', array_fill(0,round($len, 0, PHP_ROUND_HALF_DOWN),' '));
}
To use:
echo createLRPadding('Cool string');
To adjust the padding, add a second parameter:
echo createLRPadding('Cool string', 40);
The first example (default 20 pad) will write:
Cool string

PHPExcel Writter optional number of cells like GA

Can somebody tell me please how to generate column indexes (like BB) if the number of cells is optional? Currently my code explicitly sets the cell like
$list->setCellValue("D1", "Date"));
but is there a way to generate column index "D" automatically or not? I would like to have col index like GA it means from A to Z and than double the char part if columns number exceeds the range of A-Z. Is PHPExcel able to generate this indexes automatically or not?
$colIndex = PHPExcel_Cell::columnIndexFromString($cell->getColumn());
Instead of using $cell->getColumn() you can set your letter manually
So for now I has to write a function to do this:
public static function indexToExcelIndex( $index )
{
$div = intdiv( $index, 26 );
$modulo = $index % 26;
$result = '';
do
{
$result .= chr( 65 + $modulo );
}
while( --$div > -1 );
return $result;
}
EDIT: As find out there is a method setCellValueByColumnAndRow() which accepts numeric coordinates of col and row. So I dont need alphabetical coordinates.

PHP: Get width in pixel of text including "normal" text and emoji's

I want to trim a given text at a given number of pixels.
To achieve this, I loop through the length of the text and with each loop, I add the next character and measure the string with the help of the method imagettfbbox. - This works fine for me on "normal text's" e.g. like this posting. ;)
But if I add some emoji's to my text, the length is even shorter than expected. I think this is because emojis encoded with more than 1 byte. -
That's why, I'm using mb_strwidth and mb_substr.
The method imagettfbbox expects a font-file to measure the given string. This font is able to display my emoji's.
Here's my code
$Line = "🏡 Garden, 🕓 Clock, some other things";
$MaxLength = 100; // Pixel
// Start looping through the line, start with 15 characters
for ( $Len = 15; $Len < mb_strwidth($Line); $Len++ ) {
// Grep x Chars from line
$NewLine = mb_substr($Line, 0, $Len);
// Measure string
$FontBox = imagettfbbox(12, 0, "fonts/OpenSansEmoji.ttf", $NewLine);
$TextWidth = $FontBox[2];
// Compare measured string with given max length
if ( $TextWidth > $MaxLength ) {
$Line = mb_substr($Line, 0, $Len - 2) . "...";
break;
}
}
$Line = NewLine;
Expample lines
"🏡 Garden, 🕓 Clock, some other things"
"🏡🏡🏡🏡🏡🏡🏡🏡🏡🏡🏡🏡🏡🏡🏡🏡 Gaaaaaaaaaaaardeeeeeeeeeeeeeeeeeen"
"mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm"
"iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii"
"erufgbwuiergbvfuipwervbpiuwebvruiwbevuibwüeriuvbwieuörvböwieuvbr"
Result
As you can see, the more emoji's i use, the shorter the line.
Kind regards from a non native speaker. :)

Efficient way of removing extraneous zeros from prices?

I have prices stored to five decimal places of precision, such as:
1.95000
2.25000
0.01150
2.10000
2.00000
When displaying prices, I'd like to show the standard $X.XX format if the rest of the digits are just zero, but if there are significant digits then I don't want to cut them out (so I can't simply use number_format()).
As an example, the above prices should display as:
1.95
2.25
0.0115
2.10
2.00
This process has to be done on hundreds of prices per page. What's an efficient way of formatting numbers in this manner?
This uses a regex to match everything before the trailing 0s
$i = "$1.00";
$pattern = '/\$(\d+)\.(\d\d)(0*)/';
$replacement = '\$$1.$2';
print preg_replace($pattern,$replacement,$i);
Another way using rtrim on everything after the first 2 digits right of the decimal
$pos = strpos($i, '.') + 3;
print substr($i, 0, $pos) . rtrim(substr($i, $pos), '0');
This is kind of ugly but it does the job:
function formatPrice($price) {
$out = (float)$price; // Trim off right-hand 0's
$out = "$out"; // Typecast back to string
if ((strlen($out) - strpos($out, '.')) <= 2) { // Test for string length after decimal point
$out = number_format($out, 2); // Format back with 0's
}
return $out;
}
Testing it now... Works!
Here's a one-liner function from my other comment thanks to #FuzzyTree's answer:
function formatPrice($price) {
return substr($price, 0, strpos($price, '.') + 3) . rtrim(substr($price, strpos($price, '.') + 3), '0');
}

PHP: How to break a string by words within a character limit and near line breaks

I am using a terrible wrapper of PDFLib that doesn't handle the problem PDFLib has with cells that are more than the character limit (Which is around 1600 characters per cell).
So I need to break a large paragraph into smaller strings that fit neatly into the cells, without breaking up words, and as close to the end of the line as possible.
I am completely stumped about how to do this efficiently (I need it to run in a reasonable amount of time)
Here is my code, which cuts the block up into substrings based on character length alone, ignoring the word and line requirements I stated above:
SPE_* functions are static functions from the wrapper class,
SetNextCellStyle calls are used to draw a box around the outline of the cells
BeginRow is required to start a row of text.
EndRow is required to end a row of text, it must be called after BeginRow, and if the preset number of columns is not completely filled, an error is generated.
AddCell adds the string to the second parameter number of columns.
function SPE_divideText($string,$cols,$indent,$showBorders=false)
{
$strLim = 1500;
$index = 0;
$maxIndex = round((strlen($string) / 1500-.5));
$retArr= array();
while(substr($string, $strLim -1500,$strLim)!=FALSE)
{
$retArr[$index] = substr($string, $strLim -1500,$strLim);
$strLim+=1500;
SPE_BeginRow();
SPE_SetNextCellStyle('cell-padding', '0');
if($indent>0)
{
SPE_Empty($indent);
}
if($showBorders)
{
SPE_SetNextCellStyle('border-left','1.5');
SPE_SetNextCellStyle('border-right','1.5');
if($index == 0)
{
SPE_SetNextCellStyle('border-top','1.5');
}
if($index== $maxIndex)
{
SPE_SetNextCellStyle('border-bottom','1.5');
}
}
SPE_AddCell($retArr[$index],$cols-$indent);
SPE_EndRow();
$index++;
}
}
Thanks in advance for any help!
Something like this should work.
function substr_at_word_boundary($string, $chars = 100)
{
preg_match('/^.{0,' . $chars. '}(?:.*?)\b/iu', $string, $matches);
$new_string = $matches[0];
return ($new_string === $string) ? $string : $new_string;
}
$string = substr_at_word_boundary($string, 1600)

Categories