Here was my case, I saw some text shown in web pages were wider than defined width because some non-space strings were extremely longer than expected, which caused the text exceeded the width of containers (e.g. <div>), for example:
As you can see, that is a long non-space string in the text, not a long word because it contains not only alphabets and digital, but dash, equal, dot, and semi-colon signs. It turns out to be such strings exceed the width of containers and look ugly.
CSS Style
There is a way to prevent the non-space strings from exceeding the width of containers in CSS as the following.
.text {
word-break: break-all;
}
But the drawback is that it could break not only the long non-space strings but all normal words also, which decrease the readability of the text.
Preg_Replace
A better idea is to break the words only with the long non-space strings to make them fit into the width of containers. But the question is, how to recognize such strings?
Yes, the regular expression. By using PHP function preg_replace() which can match non-space strings, then we add the style 'word-break: break-all;' to them.
For example, we'd like to break the non-space strings that are longer than 80, we can do this:
$text2 = preg_replace("/(^|s)[A-Za-z0-9_.=-:]{80,}($|s)/", "<span style='word-break: break-all;'
>$0</span>", $text1);
Either way works, it all depends on your demand.
Note, Firefox may not work properly for style 'word-break: break-all;', you should add another style to solve it, which is 'display: inline-block;'.