Hopefully, I explain this well enough.

If I know the width of a container, how could I determine how many line breaks are needed to fit a given string within that space? Given a string of N-length, if it needs to wrap beyond a 3rd line, then I want to cut the string off and concatenate "..." at the end of it.

Recommended Answers

All 3 Replies

Hey I modified one of my functions do what I think you want. See how this looks...

<html>
<head>
<script>
function setstring(el,str){
	el.innerHTML = ".<br>.<br>.";
	el.setAttribute("title",str);
	var heightNeeded = el.offsetHeight;
	el.innerHTML = str;
	if (el.offsetHeight <= heightNeeded){
		return;
	}
	var tmpstr = str;
	for (var i = 0;i < str.length;i++){
		tmpstr = str.substr(0,str.length-i)+"...";
		el.innerHTML = tmpstr;
		if (el.offsetHeight <= heightNeeded){
			break;
		}
	}
}
</script>
</head>
<body>
<span id="testspan" style="border:1px solid black;width:100;display:block;"></span>
<script>
	setstring(document.getElementById('testspan'),'This is a test sentence to see if the text gets truncated correctly at 3 lines.');
</script>
</body>
</html>

Might be an easier way to do this, but I don't think you can use css to do an ellipsis in Firefox(At least you couldn't in the past). Anyway, hope this helps.

Edit: Just realized you posted this in PHP...maybe this isn't what you were looking for.

I could probably use that JS function if I have to. Then again, may as well just write the function in PHP. You've given me a place to start though.

Upon further research, I found PHP has a wordwrap function. Then I found the following site: http://www.the-art-of-web.com/php/wordwrap/.

While I don't need to explicitly break each line myself (the parent container would obviously handle word wrapping), I'm sure I can create an answer from the examples shown on the page above.

Well I see that function wraps based on character count. If that's what you want, should be easy enough to modify to work. If you're looking to constrain to a certain pixel width though, I think client side is the only way. There's no way for php to predict for sure how text is going to get rendered in the browser, so it couldn't clip based on pixel width.

If you're really looking for a php function that can measure a string based on font type/size, that's out of my league.

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.