I'm looking to display only 1 line of text from a source where characters range from 0-255. I do not want the text to exceed 1 line, and if it would, I want to truncate and display "...". What is the best way to determine if text will exceed 1 line? I tried testing by seeing how many 'W' characters could fit, which is 48, but 48 characters in other letters is much much smaller across the screen.

Thanks!!

Recommended Answers

All 3 Replies

Member Avatar for diafol

Could you use a monospace font (like Courier) which gives each letter the same width. Admittedly, this isn't the nicest looking solution.

You can truncate using:

$display_string = substr($string, 0, 48) . "…";

You could work out the relative widths of each character and count up to a certain max value. I think this would be overkill, but it's possible.

pseudocode:
start loop
get char at position 'pos'
test width of returned char
add width to total width
check against max allowed width -> IF greater than max
total chars = pos -> break loop
ELSE
increment 'pos'
END IF
end loop

Thanks for your response Ardav! I was hoping maybe there was a better approach out there than counting characters, but possibly not... I have it working with the Character Count, but I'm worried it's not the most efficient way of going about it

Member Avatar for diafol

Thanks for your response Ardav! I was hoping maybe there was a better approach out there than counting characters, but possibly not... I have it working with the Character Count, but I'm worried it's not the most efficient way of going about it

You're probably right. But I can't think of another way because as you say 'normal' fonts have different widths for different characters. The only other suggestion would be to do as you've done - find the widest character - find the max no. of those characters and use that total as your basis for truncation. However, it's not likely that you would have a complete line of max width characters - so you could probably get away with a couple more characters on top of this.
Perhaps using styling/css would make the lines look more uniform:

.one_line_text{
  text-align:justify;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.