How to wrap long lines without spaces in HTML?

PhpHtmlCssWord Wrap

Php Problem Overview


If a user types in a long line without any spaces or white space, it will break formating by going wider than the current element. Something like:

> HAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHA.............................................................................................................................................

I've tried just using wordwrap() in PHP, but the problem with that is if there is a link or some other valid HTML, it breaks.

There seems to be a few options in CSS, but none of them work in all browsers. See word-wrap in IE.

How do you solve this problem?

Php Solutions


Solution 1 - Php

in CSS3:

word-wrap:break-word

Solution 2 - Php

I was trying to solve the same problem and I found de solution here:

http://perishablepress.com/press/2010/06/01/wrapping-content/

Solution: adding to the container the following CSS properties

div {
    white-space: pre;           /* CSS 2.0 */
    white-space: pre-wrap;      /* CSS 2.1 */
    white-space: pre-line;      /* CSS 3.0 */
    white-space: -pre-wrap;     /* Opera 4-6 */
    white-space: -o-pre-wrap;   /* Opera 7 */
    white-space: -moz-pre-wrap; /* Mozilla */
    white-space: -hp-pre-wrap;  /* HP Printers */
    word-wrap: break-word;      /* IE 5+ */
}

The idea is using them all so you get better cross-browser compatibility

Hope this helps

Solution 3 - Php

I like to use the overflow: auto CSS property/value pairing. This will render the parent object the way you'd expect it to appear. If the text within the parent is too wide, scrollbars appear within the object itself. This will keep the structure the way you want it to look and provide the viewer with the ability to scroll over to see more.

Edit: the nice thing about overflow: auto compared to overflow: scroll is that with auto, the scrollbars will only appear when overflowing content exists. With scroll, the scrollbars are always visible.

Solution 4 - Php

I haven't personally used it, but Hyphenator looks promising.

Also see related (possibly duplicate) questions:

Solution 5 - Php

I'm surprised that nobody has mentioned one of my favorite solutions to this problem, the <wbr> (optional line-break) tag. It's fairly well-supported in browsers and essentially tells the browser that it can insert a line-break if it's necessary. There's also the related zero-width space character, &#8203; with the same meaning.

For the use case mentioned, displaying user comments on a web page, I would assume that there is already some output formatting to prevent injection attacks, etc. So it's simple to add these <wbr> tags every N characters in words that are too long, or in links.

This is especially useful when you need control over the format of the output, which CSS doesn't always let you do.

Solution 6 - Php

I would put the post in a div that would have a fixed width setting overflow to scroll (or to hide completely depending on the content).

so like:

#post{
	width: 500px;
	overflow: scroll;
}

But that's just me.

EDIT: As cLFlaVA points out... it is better to use auto then scroll. I do agree with him.

Solution 7 - Php

There is no "perfect" HTML/CSS solution.

The solutions either hide the overflow (ie scrolling or just hidden) or expand to fit. There is no magic.

Q: How can you fit a 100cm wide object into a space only 99cm wide?

A: You can't.

You can read break-word

EDIT

Please check out this solution https://stackoverflow.com/questions/330229/how-to-apply-a-line-wrapcontinuation-style-and-code-formatting-with-css

or

https://stackoverflow.com/questions/320184/who-has-solved-the-long-word-breaks-my-div-problem-hint-not-stackoverflow

Solution 8 - Php

I dodge the problem by not having my right sidebar fixed like that :P

Solution 9 - Php

Here's what I do in ASP.NET:

  1. Split the text field on spaces to get all the words
  2. Iterate the words looking for words that are longer than a certain amount
  3. Insert every x characters (e.g. every 25 characters.)

I looked at other CSS based ways of doing this, but didn't find anything that worked cross-browser.

Solution 10 - Php

based on Jon's suggestion the code that I created:

public static string WrapWords(string text, int maxLength)
    {
        string[] words = text.Split(' ');
        for (int i = 0; i < words.Length; i++)
        {
            if (words[i].Length > maxLength) //long word
            {
                words[i] = words[i].Insert(maxLength, " ");
                //still long ?
                words[i]=WrapWords(words[i], maxLength);
            }
        }
        text = string.Join(" ", words);
        return (text);
    }

Solution 11 - Php

I didn't want to add libraries to my pages just for word breaking. Then I wrote a simple function which I provide below, hope it helps people.

(It is breaking by 15 characters, and applying "& shy;" between, but you can change it easily in the code)

//the function:
BreakLargeWords = function (str)
{
	BreakLargeWord = function (word)
	{
		var brokenWords = [];
		var wpatt = /\w{15}|\w/igm;
		while (wmatch = wpatt.exec(word))
		{
			var brokenWord = wmatch[0];
			brokenWords.push(brokenWord);
			if (brokenWord.length >= 15) brokenWords.push("&shy;");
		}
		return brokenWords.join("");
	}

	var match;
	var word = "";
	var words = [];
	var patt = /\W/igm;
	var prevPos = 0;
	while (match = patt.exec(str))
	{
		var pos = match.index;
		var len = pos - prevPos;
		word = str.substr(prevPos, len);

		if (word.length > 15) word = BreakLargeWord(word);

		words.push(word);
		words.push(match[0]);
		prevPos = pos + 1;
	}
	word = str.substr(prevPos);
	if (word.length > 15) word = BreakLargeWord(word);
	words.push(word);
	var text = words.join("");
	return text;
}

//how to use
var bigText = "Why is this text this big? Lets do a wrap <b>here</b>! aaaaaaaaaaaaa-bbbbb-eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee";
var goodText = BreakLargeWords(bigText);

Solution 12 - Php

Add the Zero width space (&#8203;) to the string and it will wrap.

Here is a Javacript example:

let longWordWithOutSpace = 'pneumonoultramicroscopicsilicovolcanoconiosis';
// add &#8203; between every character to make it wrap
longWordWithOutSpace.split('').join('&#8203;');

Solution 13 - Php

I have posted a solution which uses JavaScript and a simple Regular Expression to break long word so that it can be wrapped without breaking your website layout.

Wrap long lines using CSS and JavaScript

Solution 14 - Php

I know that this is a really old problem and since I had the same problem I searched for a easy solution. As mentioned in the first post I decided to use the php-function wordwrap.

See the following code example for information ;-)

<?php
	$v = "reallyreallyreallylonglinkreallyreallyreallylonglinkreallyreallyreallylonglinkreallyreallyreallylonglinkreallyreallyreallylonglinkreallyreallyreallylonglink";
	$v2 = wordwrap($v, 12, "<br/>", true);
?>
<html>
	<head>
		<title>test</title>
	</head>
	<body>
		<table width="300" border="1">
			<tr height="30">
				<td colspan="3" align="center" valign="top">test</td>
			</tr>
			<tr>
				<td width="100"><a href="<?php echo $v; ?>"><?php echo $v2; ?></a></td>
				<td width="100">&nbsp;</td>
				<td width="100">&nbsp;</td>
			</tr>
		</table>
	</body>
</html>

Hope this helps.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChris BartowView Question on Stackoverflow
Solution 1 - PhpMarcinView Answer on Stackoverflow
Solution 2 - PhpFernando Costas - MercadoswebView Answer on Stackoverflow
Solution 3 - PhpcLFlaVAView Answer on Stackoverflow
Solution 4 - PhpMatt KantorView Answer on Stackoverflow
Solution 5 - PhpWylieView Answer on Stackoverflow
Solution 6 - PhpTim KnightView Answer on Stackoverflow
Solution 7 - PhpIan GView Answer on Stackoverflow
Solution 8 - PhpJimmyView Answer on Stackoverflow
Solution 9 - PhpJon GallowayView Answer on Stackoverflow
Solution 10 - PhpErsView Answer on Stackoverflow
Solution 11 - PhpCesarView Answer on Stackoverflow
Solution 12 - PhpSureshView Answer on Stackoverflow
Solution 13 - PhpHemanshu BhojakView Answer on Stackoverflow
Solution 14 - PhpMoritzView Answer on Stackoverflow