I have some text in a block with a certain width. I can count the number of lines in the text with substr($text,"<br />" but this is not the same with the number of line of the formatted text at that width. Is there a way to calculate that? Thank you.

Recommended Answers

All 2 Replies

You could get an approximate answer by dividing the number of characters in the text by the average number of characters per line in a block of the given width. It won't be perfectly accurate, but unless the block is very narrow, you will be right a good deal of the time.

Member Avatar for diafol

Well, it depends on the font-size and font-face and any font-styling, e.g. bold, italic etc. If you want something standard, you'll need to use a monospace font (e.g. Courier family) - they look ugly as hell usually, but they do the job. You also have to take account of wrapping. If the word too long to fit in a line, it will appear on the next, effectively wasting a few (or more!) characters space on the end of the first line.

However, if you do use a monospace font, you should be able to calculate this quite easily. You'll have a $max_no_chars_per_line variable, so should be straightforward. You also need to know which characters allow a wrap, e.g. '-', ' ' (most punctuation except things like quotemarks) etc.

Thinking about it, there's quite a bit involved with this. Remember that css properties may affect your output (e.g. padding) and that different browsers may display your text differently.

I'm sure that there must be a script out there for this. Somebody, somewhere must have done this before. Sounds like a job for javascript more than php, I'd say - if you're looking for an on-the-fly update.

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.