user547794
user547794

Reputation: 14511

Limiting number of characters displayed in table cell

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!

Upvotes: 0

Views: 8102

Answers (4)

Gordon
Gordon

Reputation: 316969

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

You can also control content display with the CSS property text-overflow: ellipsis

Unfortunately, browser support varies.

Upvotes: 1

Phill Pafford
Phill Pafford

Reputation: 85308

$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";

Upvotes: 0

Emil Vikstr&#246;m
Emil Vikstr&#246;m

Reputation: 91922

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

  echo $message;
}

print_dots($long_text);

Upvotes: 0

Burak Guzel
Burak Guzel

Reputation: 1285

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

Upvotes: 9

Related Questions