Code for word wrap

Editor’s note: This complete guide to word-wrap, overflow-wrap, and word-break in CSS was last updated 24 February 2023 to reflect the reflect the most recent version of CSS, include interactive code examples, and include a section on how to wrap text using CSS. To learn more about the overflow property, check out our guide to CSS overflow.

Making a site responsive so that it displays correctly on all devices is very important in this day and age. Unfortunately, despite your best efforts to do so, you may still end up with broken layouts. Broken layouts can happen when certain words are too long to fit in their container. Content overflow can occur when you are dealing with user-generated content you have no control over, such as the comments section of a post. Therefore, you need to apply styling to prevent content from overflowing their container.

Content overflow is a common problem for frontend developers. On the web, overflow occurs when your content doesn’t fit entirely within its containing element. As a result, it spills outside. In CSS, you can manage content overflow mainly using the overflow, word-wrap, overflow-wrap, and word-break CSS properties. However, our focus in this article will be on the word-wrap, overflow-wrap, and word-break CSS properties.

Jump ahead:

  • Using word-wrap, overflow-wrap, and word-break CSS properties
    • How does content wrapping occur in browsers?
    • What is the difference between a soft wrap break and a forced line break?
  • Understanding the Word-wrap and overflow-wrap CSS properties
    • Normal
    • Anywhere
    • Break-word
  • Implementing the Word-break CSS property
    • Setting word-break to Normal
    • The Break-all value
    • Using the Keep-all value
  • What is the difference between overflow-wrap and word-break?
  • How to wrap text using CSS
  • Troubleshooting CSS content overflow with Chrome DevTools

Using word-wrap, overflow-wrap, and word-break CSS properties

You can use the word-wrap, overflow-wrap, or word-break CSS properties to wrap or break words that would otherwise overflow their container. This article is an in-depth tutorial on the word-wrap, overflow-wrap, and word-break CSS properties and how you can use them to prevent content overflow from ruining your nicely styled layout. Before we get started, let us understand how browsers wrap content in the next section.

How does content wrapping occur in browsers?

Browsers and other user agents perform content wrapping at allowed breakpoints, referred to as soft wrap opportunities. A browser will wrap content at a soft wrap opportunity, if one exists, to minimize content overflow. In English and other similar writing systems, soft wrap opportunities occur by default at word boundaries in the absence of hyphenation. Because words are bound by spaces and punctuation, that is where soft wraps occur.

Although soft wraps occur in space characters in English texts, the situation might be different for non-English writing systems. Some languages do not use spaces to separate words, meaning that content wrapping depends on the language or writing system. The value of the lang attribute you specify on the HTML element is mostly used to determine which language system is used.

This article will focus mainly on the English language writing system. The default wrapping at soft wrap opportunities may not be sufficient if you are dealing with long, continuous text, such as URLs or user-generated content, which you have very little or no control over. Before we go into a detailed explanation of these CSS properties, let’s look at the differences between soft wrap break and forced line break in the section below.

What is the difference between a soft wrap break and a forced line break?

Any text wrap that occurs at a soft wrap opportunity is referred to as a soft wrap break. For wrapping to occur at a soft wrap opportunity, you need to make sure you’ve enabled wrapping. For example, setting the value of white-space CSS property to nowrap will disable wrapping. Forced line breaks are caused by explicit line-breaking controls or line breaks marking the end or start of blocks of text.

Understanding the Word-wrap and overflow-wrap CSS properties

The name word-wrap is the legacy name for the overflow-wrap CSS property. Word-wrap was originally a non-prefixed Microsoft extension and was not part of the CSS standard, though most browsers implemented it with the name word-wrap. According to the draft CSS3 specification, browsers should treat word-wrap as a legacy name alias of the overflow-wrap property for compatibility.

Most recent versions of popular web browsers have implemented the overflow-wrap property. The draft CSS3 specification refers to the overflow-wrap property as:

This property specifies whether the browser may break at otherwise disallowed points within a line to prevent overflow when an otherwise-unbreakable string is too long to fit within the line box.

If you have a white-space property on an element, you need to set its value to allow wrapping for overflow-wrap to have an effect. Below are the values of the overflow-wrap property:

overflow-wrap: normal;
overflow-wrap: anywhere;
overflow-wrap: break-word;

You can also use the global values inherit, initial, revert, and unset with overflow-wrap, but we won’t cover them here. In the subsections below, we will look at the values of the overflow-wrap CSS property outlined above to understand the behavior of this property.

Normal

Applying the value normal will make the browser use the default line-breaking behavior of the system. For English and other related writing systems, line breaks will therefore occur at whitespaces and hyphens, as shown below:

.my-element{
    overflow-wrap: normal;
}

In the example below, there is a word in the text that is longer than its container. Because there is no soft wrap opportunity and the value of the overflow-wrap property is normal, the word overflows its container. It describes the default line-breaking behavior of the system:

See the Pen
overflow-wrap-normal by Joseph Mawa (@nibble0101)
on CodePen.

Anywhere

Using the value anywhere will break an otherwise unbreakable string at arbitrary points between two characters. It will not insert a hyphen character even if you apply the hyphens property on the same element.

The browser will break the word only if displaying the word on its line will cause an overflow. If the word still overflows when placed on its line, it will break the word at the point where an overflow would otherwise occur. When you use anywhere, the browser will consider the soft wrap opportunities introduced by the word break when calculating min-content intrinsic sizes:

.my-element{
   overflow-wrap: anywhere;
}

Unlike in the previous section, where we used overflow-wrap: normal, in the example below, we are using overflow-wrap: anywhere. The overflowing word that is otherwise unbreakable is broken into chunks of text using overflow-wrap: anywhere so that it fits in its container:

See the Pen
overlow-wrap-anywhere by Joseph Mawa (@nibble0101)
on CodePen.

Most recent versions of desktop browsers support overflow-wrap: anywhere. However, support for some mobile browsers is either lacking or unknown. The image below shows the browser support:

CSS Overflow-Wrap Compatibility

Break-word

The value break-word is like anywhere in terms of functionality. If the browser can wrap the overflowing word to its line without overflowing, that is what it will do. However, if the word still overflows its container even when it is on its line, the browser will break it at the point where the overflow would otherwise occur:

.my-element{
   overflow-wrap: break-word;
}

The example below shows how the browser breaks the overflowing text when you apply overflow-wrap: break-word:

See the Pen
overflow-wrap-break-word by Joseph Mawa (@nibble0101)
on CodePen.

Notice that the text appears the same as in the last subsection. The difference between overflow-wrap: anywhere and overflow-wrap: break-word is in the min-content intrinsic sizes.

The difference between anywhere and break-word is apparent when calculating the min-content intrinsic sizes. With break-word, the browser doesn’t consider the soft wrap opportunities introduced by the word break when calculating min-content intrinsic sizes, but it does with anywhere. For more about min-content intrinsic sizes, check out our guide here.

The value break-word has decent coverage among the most recent versions of desktop browsers. Unfortunately, you cannot say the same about their mobile counterpart. It is, therefore, safer to use the legacy word-wrap: break-word instead of the more recent overflow-wrap: break-word.

The image below shows browser support for overflow-wrap: break-word:

CSS Break-Word Compatibility

The most recent versions of desktop browsers have support, while support for some mobile browsers is unknown.

Implementing the Word-break CSS property

Word-break is another CSS property you can use to specify soft wrap opportunities between characters. You can use this property to break a word at the exact spot where an overflow would occur and wrap it onto the following line.

The draft CSS3 specification refers to the word-break CSS property as:

This property specifies soft wrap opportunities between letters, i.e., where it is “normal” and permissible to break lines of text. It controls what types of letters the browser can glom together to form unbreakable “words” — causing CJK characters to behave like non-CJK text or vice versa.

Below are the possible values of the word-break CSS property. Like overflow-wrap, you can use the global values inherit, initial, revert, and unset with word-break, but we won’t cover them here:

word-break: normal;
word-break: break-all;
word-break: keep-all;

Break-word is also a value of the word-break CSS property, though it was removed. However, browsers still support it for legacy reasons. Specifying this property has the same effect as word-break: normal and overflow-wrap: anywhere.

Now that we know the break-word CSS property and its corresponding values, let us look at them in the subsections below.

Setting word-break to Normal

Setting the value of the word-break property to normal will apply the default word breaking rules:

.my-element{
   word-break: normal;
}

The example below illustrates what happens when you apply the styling word-break: normal to a block of text that contains a word longer than its container:

See the Pen
word-break-normal by Joseph Mawa (@nibble0101)
on CodePen.

What you see is the browser’s usual word-breaking rules in effect.

The Break-all value

The value break-all will insert a line break at the exact point where the text would otherwise overflow for non-Chinese, non-Japanese, and non-Korean writing systems. It will not put the word on its own line, even if doing so will prevent the need to insert a line break:

.my-element{
   word-break: break-all;
}

In the example below, I am applying word-break: break-all styling to a p element of width 240px containing an overflowing text. The browser will insert a line break at the point where an overflow would occur and wrap the remaining text to the following line:

See the Pen
word-break-break-all by Joseph Mawa (@nibble0101)
on CodePen.

Using break-all will break a word between two characters at the exact point where an overflow would occur in English and other related language systems. However, it won’t apply the same behavior to Chinese, Japanese, and Korean (CJK) texts.

It doesn’t apply the same behavior for CJK texts because CJK writing systems have their own rules for applying breakpoints. Creating a line break between two characters arbitrarily just for the sake of avoiding overflow might significantly change the overall meaning of the text. For CJK systems, the browser will apply line breaks at the point where such breaks are allowed.

Using the Keep-all value

If you use the value keep-all, the browser will not apply word breaks to CJK texts, even if there is content overflow. The effect of applying keep-all value is the same as that of normal for non-CJK writing systems:

.my-element{
   word-break: keep-all;
}

In the example below, applying word-break: keep-all will have the same effect as word-break: normal for a non-CJK writing system such as English:

See the Pen
word-break-keep-all by Joseph Mawa (@nibble0101)
on CodePen.

The image below shows the browser support for word-break: keep-all:

CSS Keep-all Compatibility

This value has support in most popular desktop browsers. Unfortunately, it is not the case for mobile browsers. Now that we have looked at the overflow-wrap and word-break CSS properties, what is the difference between the two? The section below will shed light on that.

What is the difference between overflow-wrap and word-break?

You can use the CSS properties overflow-wrap and word-break to manage content overflow. However, there are differences in the way the two properties handle it.

Using overflow-wrap will wrap the entire overflowing word to its line if it can fit in a single line without overflowing its container. The browser will break the word only if it cannot place it on a new line without overflowing. In most cases, the overflow-wrap property or its legacy name word-wrap might manage content overflow. Using word-wrap: break-word will wrap the overflowing word onto a new line and goes ahead to break it between two characters if it still overflows its container.

Word-break will ruthlessly break the overflowing word between two characters even if placing it on its line will negate the need for word break. Some writing systems, like the CJK writing systems, have strict word breaking rules the browser takes into consideration when creating line breaks using word-break.

How to wrap text using CSS

As hinted above, if you want to wrap text or break a word overflowing the confines of its box, your best bet is the overflow-wrap CSS property. You can also use its legacy name, word-wrap. Try the word-break CSS property if the overflow-wrap property doesn’t work for you. However, be aware of the differences between overflow-wrap and word-break highlighted above.

Below is an illustration of the overflow-wrap and word-wrap CSS properties. You can play with the CodePen to understand their effects:

See the Pen
how-to-wrap-text by Joseph Mawa (@nibble0101)
on CodePen.

Troubleshooting CSS content overflow with Chrome DevTools

More often than not, you might need to fix broken layouts caused by content overflow, as complex user interfaces are now commonplace in frontend development. Modern web browsers come with tools for troubleshooting such layout issues, such as Chrome DevTools.

It provides the capability to select an element in the DOM tree so that you can view, add, and remove CSS declarations and much more. It will help you track down the offending CSS style in your layout and fix it with ease.

To open the Chrome DevTools, you can use the F12 key. When open, it looks like in the image below. Selecting an element in the DOM tree will display its corresponding CSS styles. You can modify the styles and see the effect on your layout as you track down the source of the bug:

Using Chrome DevTools With CSS

As already mentioned, if you have white-space property on an element, set its value to allow wrapping for overflow-wrap: anywhere or overflow-wrap: break-word to work.

Setting the value of overflow-wrap property to anywhere or break-word on a table content won’t break an overflowing word like in the examples above. The table will overflow its container and create a horizontal scroll if necessary. To get the table to fit within its container and overflow-wrap to work, set the value of the table-layout property to fixed and set the table width to 100% or to some fixed value.

Conclusion

As pointed out in the above sections, overflow-wrap and word-break are similar in so many ways, and you can use both of them for line-breaking controls. The name overflow-wrap is an alias of the legacy word-wrap property. Therefore, you can use the two interchangeably. However, it is worth mentioning that the browser support for the newer overflow-wrap property is still low. You are better off using word-wrap instead of overflow-wrap if you want near-universal browser support.

According to the draft CSS3 specification, browsers and user agents should continue supporting word-wrap for legacy reasons. If you are looking to manage content overflow, overflow-wrap or its legacy name word-wrap might be sufficient. You can also use word-break to break a word between two characters if the word overflows its container. Just like overflow-wrap, you need to tread with caution when using word-break because of limitations in the browser support.

Now that you know the behavior associated with the two properties, you can decide where and when to use them. Did I miss anything? Leave a comment in the comments section. I will be happy to update this article.

Is your frontend hogging your users’ CPU?

As web frontends get increasingly complex, resource-greedy features demand more and more from the browser. If you’re interested in monitoring and tracking client-side CPU usage, memory usage, and more for all of your users in production, try LogRocket.LogRocket Dashboard Free Trial Bannerhttps://logrocket.com/signup/

LogRocket is like a DVR for web and mobile apps, recording everything that happens in your web app, mobile app, or website. Instead of guessing why problems happen, you can aggregate and report on key frontend performance metrics, replay user sessions along with application state, log network requests, and automatically surface all errors.

Modernize how you debug web and mobile apps — Start monitoring for free.

How can text like aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa which exceeds the width of a div (say 200px) be wrapped?

I am open to any kind of solution such as CSS, jQuery, etc.

trejder's user avatar

trejder

17k27 gold badges123 silver badges215 bronze badges

asked Jul 18, 2009 at 15:56

Satya Kalluri's user avatar

Satya KalluriSatya Kalluri

5,1084 gold badges27 silver badges37 bronze badges

Try this:

div {
    width: 200px;
    word-wrap: break-word;
}

answered Jul 18, 2009 at 16:02

Alan Haggai Alavi's user avatar

Alan Haggai AlaviAlan Haggai Alavi

72.2k19 gold badges101 silver badges127 bronze badges

6

On bootstrap 3, make sure the white-space is not set as ‘nowrap’.

div {
  width: 200px;
  word-break: break-all;
  white-space: normal;
}

answered Nov 12, 2013 at 8:39

lukaserat's user avatar

2

You can use a soft hyphen like so:

aaaaaaaaaaaaaaa­aaaaaaaaaaaaaaa

This will appear as

aaaaaaaaaaaaaaa-
aaaaaaaaaaaaaaa

if the containing box isn’t big enough, or as

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

if it is.

Tunaki's user avatar

Tunaki

131k46 gold badges330 silver badges415 bronze badges

answered Jul 18, 2009 at 16:13

Kim Stebel's user avatar

Kim StebelKim Stebel

41.6k12 gold badges125 silver badges142 bronze badges

7

div {
    /* Set a width for element */
    word-wrap: break-word
}

The ‘word-wrap‘ solution only works in IE and browsers supporting CSS3.

The best cross browser solution is to use your server side language (php or whatever) to locate long strings and place inside them in regular intervals the html entity
This entity breaks the long words nicely, and works on all browsers.

e.g.

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa​aaaaaaaaaaaaaaaaaaaaaaaaaaaaa

code's user avatar

code

5,1204 gold badges16 silver badges37 bronze badges

answered Jul 18, 2009 at 16:14

Orr Siloni's user avatar

Orr SiloniOrr Siloni

1,24010 silver badges20 bronze badges

1

This worked for me

word-wrap: normal;
word-break: break-all;
white-space: normal;
display: block;
height: auto;
margin: 3px auto;
line-height: 1.4;
-webkit-line-clamp: 1;
-webkit-box-orient: vertical;

answered Jun 2, 2016 at 2:04

Amol's user avatar

AmolAmol

9087 silver badges20 bronze badges

1

The only one that works across IE, Firefox, chrome, safari and opera if there are no spaces in the word (such as a long URL) is:

div{
    width: 200px;  
    word-break: break-all;
}

I found this to be bullet-proof.

Radek Postołowicz's user avatar

answered Apr 12, 2013 at 13:56

Kyle Dearle's user avatar

Kyle DearleKyle Dearle

1291 gold badge2 silver badges9 bronze badges

0

Another option is also using:

div
{
   white-space: pre-line;
}

This will set all your div elements in all browsers that support CSS1 (which is pretty much all common browsers as far back as IE 8)

answered Oct 14, 2014 at 15:59

Andrew Marais's user avatar

1

Cross Browser

.wrap
{
    white-space: pre-wrap; /* css-3 */    
    white-space: -moz-pre-wrap; /* Mozilla, since 1999 */
    white-space: -pre-wrap; /* Opera 4-6 */    
    white-space: -o-pre-wrap; /* Opera 7 */    
    word-wrap: break-word; /* Internet Explorer 5.5+ */
}

Community's user avatar

answered Apr 20, 2015 at 9:21

Timeless's user avatar

TimelessTimeless

7,2898 gold badges60 silver badges94 bronze badges

<p style="word-wrap: break-word; word-break: break-all;">
    Adsdbjf bfsi hisfsifisfsifs shifhsifsifhis aifoweooweoweweof
</p>

answered Oct 1, 2020 at 20:23

Manoj Alwis's user avatar

Manoj AlwisManoj Alwis

1,27911 silver badges24 bronze badges

Example from CSS Tricks:

div {
    -ms-word-break: break-all;

    /* Be VERY careful with this, breaks normal words wh_erever */
    word-break: break-all;

    /* Non standard for webkit */
    word-break: break-word;

    -webkit-hyphens: auto;
    -moz-hyphens: auto;
    hyphens: auto;
}

More examples here.

answered Feb 4, 2015 at 10:01

Juraj Guniš's user avatar

In HTML body try:

<table>
    <tr>
        <td>
            <div style="word-wrap: break-word; width: 800px">
                Hello world, how are you? More text here to see if it wraps after a long while of writing and it does on Firefox but I have not tested it on Chrome yet. It also works wonders if you have a medium to long paragraph. Just avoid writing in the CSS file that the words have to break-all, that's a small tip.
            </div>
        </td>
    </tr>
</table>

In CSS body try:

background-size: auto;

table-layout: fixed;

John Slegers's user avatar

John Slegers

44.5k22 gold badges201 silver badges169 bronze badges

answered Feb 6, 2016 at 17:06

Wesson2's user avatar

Add this CSS to the paragraph.

width:420px; 
min-height:15px; 
height:auto!important; 
color:#666; 
padding: 1%; 
font-size: 14px; 
font-weight: normal;
word-wrap: break-word; 
text-align: left;

TylerH's user avatar

TylerH

20.6k64 gold badges76 silver badges97 bronze badges

answered May 23, 2012 at 9:53

Swapnil Godambe's user avatar

Swapnil GodambeSwapnil Godambe

2,0541 gold badge24 silver badges28 bronze badges

1

Try this

div{
  display: block;
  display: -webkit-box;
  height: 20px;
  margin: 3px auto;
  font-size: 14px;
  line-height: 1.4;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

the property text-overflow: ellipsis add … and line-clamp show the number of lines.

answered Nov 27, 2014 at 21:10

Vladimir Salguero's user avatar

I have used bootstrap.
My html code looks like ..

<div class="container mt-3" style="width: 100%;">
  <div class="row">
    <div class="col-sm-12 wrap-text">
      <h6>
        text content
      </h6>
    </div>
  </div>
</div>

CSS

.wrap-text {
     text-align:justify;
}

Stephen Rauch's user avatar

Stephen Rauch

47.2k31 gold badges110 silver badges133 bronze badges

answered Sep 18, 2018 at 2:24

Rahul Wasnik's user avatar

1

you can use this CSS

p {
  width: min-content;
  min-width: 100%;
}

answered Dec 27, 2019 at 10:22

Rashid Iqbal's user avatar

Rashid IqbalRashid Iqbal

1,05313 silver badges12 bronze badges

Try this CSS property —

overflow-wrap: anywhere;

answered Jun 9, 2022 at 6:12

Akshay Chavan's user avatar

A server side solution that works for me is: $message = wordwrap($message, 50, "<br>", true); where $message is a string variable containing the word/chars to be broken up. 50 is the max length of any given segment, and "<br>" is the text you want to be inserted every (50) chars.

answered Jan 23, 2012 at 7:31

deshbanks's user avatar

1

Try this

div {display: inline;}

answered Jul 18, 2018 at 16:58

Michael Mulikita's user avatar

try:

overflow-wrap: break-word;

borchvm's user avatar

borchvm

3,48411 gold badges45 silver badges43 bronze badges

answered Jan 29, 2020 at 3:00

Eden Sharvit's user avatar

Use word-wrap:break-word attribute along with required width. Mainly, put
the width in pixels, not in percentages.

width: 200px;
word-wrap: break-word;

JSuar's user avatar

JSuar

21.1k4 gold badges43 silver badges82 bronze badges

answered Jan 27, 2011 at 8:36

aks's user avatar

1

Example

Allow long words to be able to break and wrap onto the next line:

div {
  word-wrap: break-word;
}

Try it Yourself »


Definition and Usage

The word-wrap property allows long words to be able to be broken and wrap
onto the next line.

Show demo ❯

Default value: normal
Inherited: yes
Animatable: no. Read about animatable
Version: CSS3
JavaScript syntax: object.style.wordWrap=»break-word»
Try it

Browser Support

The numbers in the table specify the first browser version that fully supports the property.

Property
word-wrap 4.0 5.5 3.5 3.1 10.5

CSS Syntax

word-wrap: normal|break-word|initial|inherit;

Property Values

Value Description Demo
normal Break words only at allowed break points. This is default Demo ❯
break-word Allows unbreakable words to be broken Demo ❯
initial Sets this property to its default value. Read about initial
inherit Inherits this property from its parent element. Read about inherit

Related Pages

CSS tutorial: CSS Text Effects

Полное руководство по word-wrap, overflow-wrap и word-break в CSS

От автора: в наши дни очень важно сделать сайт адаптивным, чтобы он правильно отображался на всех устройствах. К сожалению, несмотря на все усилия, вы все равно можете получить неработающие макеты. Иногда макеты нарушаются из-за того, что некоторые слова слишком длинные, чтобы уместиться в контейнере.

Переполнение контента может произойти, когда вы имеете дело с пользовательским контентом, который вы не можете контролировать. Типичный пример — раздел комментариев в блоге. Следовательно, вам необходимо применить соответствующий стиль, чтобы содержимое не переполняло свой контейнер.

Вы можете использовать свойства CSS word-wrap, overflow-wrap или word-break для обертывания или переноса слов, которые в противном случае переполнили бы их контейнер. Эта статья представляет собой подробное руководство по свойствам CSS word-wrap, overflow-wrap и word-break, а также о том, как вы можете использовать их, чтобы не допустить, чтобы переполнение содержимого разрушало ваш красиво оформленный макет.

Прежде чем мы начнем, давайте разберемся, как браузеры переносят контент в следующую секцию.

Как происходит перенос контента в браузерах?

Браузеры выполняют перенос содержимого в разрешенные брейкпоинты, называемый «мягкой оберткой». Браузер будет обертывать контент с использованием мягкой обертки, если таковая возможна, чтобы минимизировать переполнение контента.

Практический курс по верстке адаптивного сайта с нуля!

Изучите курс и узнайте, как верстать современные сайты на HTML5 и CSS3

Узнать подробнее

В английской и большинстве подобных ей системах письма возможности мягкой обертки по умолчанию появляются на границах слов при отсутствии переносов. Поскольку слова ограничены пробелами и знаками препинания, именно здесь используются мягкие обертки.

Хотя в английских текстах для символов пробела используются мягкие обертки, для неанглийских систем письма ситуация может быть иной. Некоторые языки не используют пробелов для разделения слов. Следовательно, упаковка содержимого зависит от языка или системы письма. Значение атрибута lang, которое вы указываете в элементе html, в основном используется для определения того, какая языковая система используется. В этой статье основное внимание будет уделено системе письма на английском языке.

Переноса по умолчанию при использовании мягкой обертки может быть недостаточно, если вы имеете дело с длинным непрерывным текстом, например URL-адресами или пользовательским контентом, который у вас недостаточно или совсем не контролируется.

Прежде чем мы перейдем к подробному объяснению этих свойств CSS, давайте посмотрим на различия между мягким переносом и принудительным переносом строки в разделе ниже.

В чем разница между мягким и принудительным переносом строки?

Любой перенос текста, который происходит при использовании мягкого переноса, называется разрывом мягкого переноса. Чтобы перенос происходил при использовании мягкого обертывания, необходимо убедиться, что обертывание включено. Например, установка значения nowrap для свойства white-space отключит перенос.

С другой стороны, принудительные разрывы строк возникают из-за явного управления разрывом строк или указания конца или начала блоков текста.

CSS свойства word-wrap и overflow-wrap

Название word-wrap — это устаревшее имя свойства overflow-wrap. Word-wrap изначально было расширением Microsoft. Оно не было частью стандарта CSS, хотя большинство браузеров реализовали его под названием word-wrap. Согласно проекту спецификации CSS3, браузеры должны рассматривать word-wrap как устаревший псевдоним для свойства overflow-wrap.

В последних версиях популярных веб-браузеров реализовано свойство overflow-wrap. В проекте спецификации CSS3 указано следующее определение overflow-wrap: Это свойство указывает, может ли браузер разбивать строку на недопустимые точки переноса, чтобы предотвратить переполнение, когда неразрывная строка слишком длинна, чтобы поместиться в границах контейнера.

Если у вас есть свойство white-space для элемента, вам необходимо установить для него значение allow, чтобы разрешить эффект переноса для overflow-wrap. Ниже приведены значения свойства overflow-wrap. Вы также можете использовать глобальные значения inherit, initial, revert и unset для overflow-wrap, но здесь мы не будем их рассматривать.

overflow-wrap: normal;

overflow-wrap: anywhere;

overflow-wrap: break-word;

Ниже мы рассмотрим значения свойства CSS overflow-wrap, чтобы понять его поведение.

Normal

Применение значения normal заставит браузер использовать поведение разрыва строки по умолчанию в системе. Поэтому для английского языка и других подобных системах письма разрывы строк будут происходить через пробелы и дефисы:

.my-element{

    overflow-wrap: normal;

}

На изображении ниже в тексте есть слово, длина которого превышает длину контейнера. Поскольку нет возможности мягкого переноса, а значение свойства overflow-wrap равно normal, слово переполняет свой контейнер. Это является поведением системы при переносе строк по умолчанию.

Полное руководство по word-wrap, overflow-wrap и word-break в CSS

Anywhere

Использование значения в аnywhere приведет к разрыву неразрывной строки в произвольных точках между двумя символами. Аnywhere не будет добавлять символ дефиса, даже если вы примените свойство hyphens к этому элементу.
Браузер разорвет слово только в том случае, если отображение слова приведет к переполнению. Если слово вызывает переполнение, оно будет разорвано в точке, где это переполнение произошло.

Когда вы используете аnywhere, браузер будет учитывать возможности мягкого переноса, предоставляемые разрывом слова, при вычислении внутренних размеров min-content:

.my-element{

   overflow-wrap: anywhere;

}

В отличие от предыдущего примера, где мы использовали overflow-wrap: normal, на изображении ниже мы используем overflow-wrap :where. Слово-переполнение, которое невозможно разбить, разбивается на фрагменты текста с помощью overflow-wrap: anywhere, чтобы оно поместилось в своем контейнере.

Полное руководство по word-wrap, overflow-wrap и word-break в CSS

Значение anywhere не поддерживается некоторыми браузерами. На изображении ниже показана поддержка браузерами по данным caniuse.com. Поэтому не рекомендуется использовать overflow-wrap: anywhere, если вы хотите иметь более высокую поддержку браузера.

Полное руководство по word-wrap, overflow-wrap и word-break в CSS

Break-word

Значение break-word похоже на любое другое с точки зрения функциональности. Если браузер может перенести слово без переполнения, то он это сделает. Однако, если слово все еще переполняет контейнер, даже когда оно находится в новой строке, браузер разделит его в точке, где снова произошло бы переполнение:

.my-element{

   overflow-wrap: break-word;

}

На изображении ниже показано, как браузер прерывает переполненный текст в предыдущем разделе, когда вы применяете overflow-wrap: break-word. Вы заметите, что изображение ниже выглядит так же, как изображение в последнем примере. Разница между overflow-wrap: anywhere и overflow-wrap: break-word заключается в вычислении внутренних размеров min-content.

Полное руководство по word-wrap, overflow-wrap и word-break в CSS

Разница между anywhere и break-word очевидна при вычислении внутренних размеров min-content. С break-word браузер не учитывает возможности мягкого переноса, предоставляемые разрывом слова, при вычислении внутренних размеров min-content, но он учитывает возможности мягкого переноса при использовании anywhere.

Значение break-word имеет достойный охват среди последних версий десктопных браузеров. К сожалению, этого нельзя сказать об их мобильном аналоге. Поэтому безопаснее использовать унаследованный word-wrap: break-word вместо более нового overflow-wrap: break-word.

На изображении ниже показана поддержка браузеров overflow-wrap: break-word согласно caniuse.com. Вы заметите, что последние версии десктопных браузеров имеют поддержку, в то время как поддержка некоторых мобильных браузеров неизвестна.

Полное руководство по word-wrap, overflow-wrap и word-break в CSS

Свойство Word-break

Word-break — еще одно свойство CSS, которое вы можете использовать для указания возможности мягкого переноса между символами. Вы можете использовать это свойство, чтобы разбить слово в том месте, где могло произойти переполнение, и перенести его на следующую строку.

Ниже приводится то, что говорится о свойстве CSS word-break в спецификации CSS3:

Практический курс по верстке адаптивного сайта с нуля!

Изучите курс и узнайте, как верстать современные сайты на HTML5 и CSS3

Узнать подробнее

Это свойство определяет возможности мягкого переноса между буквами, то есть там, где это «нормально» и допустимо для разрывов строк текста. Word-break контролирует, какие типы букв браузер может объединять в неразрывные «слова», заставляя символы CJK вести себя как текст, не относящийся к CJK, или наоборот.

Ниже приведены возможные значения CSS-свойства word-break. Как и для overflow-wrap, вы также можете использовать глобальные значения inherit, initial, revert и unset, но мы не будем рассматривать их здесь:

word-break: normal;

word-break: break-all;

word-break: keep-all;

Break-word также является значением для CSS-свойства word-break, хотя оно устарело. Однако, браузеры по-прежнему поддерживают его. Указание этого свойства имеет тот же эффект, что и word-break: normal и overflow-wrap :where.

Теперь, когда мы знакомы с CSS-свойством break-word и соответствующими ему значениями, давайте подробно рассмотрим их.

Normal

Установка для свойства word-break значение normal будет применять правила разбиения по словам по умолчанию:

.my-element{

   word-break: normal;

}

На изображении ниже показано, что происходит, когда вы применяете стиль word-break: normal к блоку текста, который содержит слово длиннее, чем его контейнер. Вы видите, что в браузере действуют обычные правила разбиения на слова.

Полное руководство по word-wrap, overflow-wrap и word-break в CSS

Break-all

Значение break-all вставит разрыв строки именно в том месте, где текст переполнился бы для некитайских, неяпонских и некорейских систем письма. Слово не будет помещено в отдельную строку, даже если это предотвратит необходимость вставки разрыва строки:

.my-element{

   word-break: break-all;

}

На изображении ниже я применил стиль word-break:break-all к элементу p шириной 240 пикселей, содержащему переполненный текст. Браузер вставил разрыв строки в точке, где могло произойти переполнение, и перенес оставшийся текст в следующую строку.

Полное руководство по word-wrap, overflow-wrap и word-break в CSS

Использование break-all приведет к разрыву слова между двумя символами именно в том месте, где произойдет переполнение в английском и других родственных языковых системах. Однако это не применимо к текстам на китайском, японском и корейском языках (CJK).

Он не применяет то же поведение к текстам CJK, потому что системы письма CJK имеют свои собственные правила для применения брейкпоинтов. Создание разрыва строки между двумя символами произвольно во избежание переполнения может значительно изменить общий смысл текста. Для систем CJK браузер будет применять разрывы строк в том месте, где такие разрывы разрешены.

На изображении ниже показана поддержка браузером word-break: break-word согласно caniuse.com. Хотя последние версии современных веб-браузеров поддерживают это значение, поддержка среди некоторых мобильных браузеров неизвестна.

Полное руководство по word-wrap, overflow-wrap и word-break в CSS

Keep-all

Если вы используете значение keep-all, браузер не будет применять разрывы слов к текстам CJK, даже если происходит переполнение содержимого. Эффект от применения значения keep-all такой же, как и у normal для систем письма, отличных от CJK:

.my-element{

   word-break: keep-all;

}

На изображении ниже применение word-break: keep-all имеет тот же эффект, что и word-break: normal, потому что я использую систему письма, отличную от CJK (английский язык).

Полное руководство по word-wrap, overflow-wrap и word-break в CSS

На изображении ниже показана поддержка браузером word-break: keep-all согласно caniuse.com. Это значение поддерживается в большинстве популярных десктопных браузеров. К сожалению, это не относится к мобильным браузерам.

Полное руководство по word-wrap, overflow-wrap и word-break в CSS

Теперь, когда мы рассмотрели свойства CSS overflow-wrap и word-break, в чем разница между ними?

В чем разница между overflow-wrap и разр word-break?

Вы можете использовать CSS свойства overflow-wrap и word-break для управления переполнением содержимого. Однако существуют различия в способах обработки этих двух свойств.

Использование overflow-wrap приведет к переносу всего переполненного слова в новую строку, если оно может поместиться в одну строку, не переполняя свой контейнер. Браузер разорвет слово только в том случае, если он не сможет разместить слово в новой строке без переполнения. В большинстве случаев свойство overflow-wrap или его устаревшее название word-wrap может быть достаточным для управления переполнением содержимого.

Свойство overflow-wrap относительно новое, поэтому его поддержка браузером ограничена. Вместо этого вы можете использовать устаревшее название word-wrap, если вам нужна более высокая поддержка браузером.

С другой стороны, word-break безжалостно разорвет слово, которое выходит за границы, между двумя символами, даже если размещение его в новой строке устранит необходимость в разрыве слова. Кроме того, некоторые системы письма, такие как системы письма CJK, имеют строгие правила разбиения по словам, которые браузер принимает во внимание при создании разрывов строк с помощью word-break.

Заключение

Как указывалось в предыдущих разделах, overflow-wrap и word-break во многом схожи. Вы можете использовать оба из них для управления разрывом строки.

Название overflow-wrap является псевдонимом устаревшего свойства word-wrap. Следовательно, вы можете использовать их как взаимозаменяемые. Однако стоит отметить, что поддержка браузером нового свойства overflow-wrap по-прежнему невысока. Вам лучше использовать word-wrap вместо overflow-wrap, если вы хотите почти универсальную поддержку браузера. Согласно проекту спецификации CSS3, браузеры должны продолжать поддерживать word-wrap.

Если вы хотите управлять переполнением содержимого, вам достаточно использовать overflow-wrap или его устаревшее название word-wrap.

Вы также можете использовать word-break, чтобы разбить слово между двумя символами, если слово выходит за пределы своего контейнера. Как и при overflow-wrap, при использовании word-break нужно действовать осторожно из-за ограничений в поддержке браузера.

Теперь, когда вы знаете поведение, связанное с этими двумя свойствами, вы можете решить, где и когда их использовать.

Автор: Joseph Mawa

Источник: blog.logrocket.com

Редакция: Команда webformyself.

Читайте нас в Telegram, VK, Яндекс.Дзен

Практический курс по верстке адаптивного сайта с нуля!

Изучите курс и узнайте, как верстать современные сайты на HTML5 и CSS3

Узнать подробнее

PSD to HTML

Практика верстки сайта на CSS Grid с нуля

Смотреть

(PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8)

wordwrapWraps a string to a given number of characters

Description

wordwrap(
    string $string,
    int $width = 75,
    string $break = «n»,
    bool $cut_long_words = false
): string

Parameters

string

The input string.

width

The number of characters at which the string will be wrapped.

break

The line is broken using the optional
break parameter.

cut_long_words

If the cut_long_words is set to true, the string is
always wrapped at or before the specified width. So if you have
a word that is larger than the given width, it is broken apart.
(See second example). When false the function does not split the word
even if the width is smaller than the word width.

Return Values

Returns the given string wrapped at the specified length.

Examples

Example #1 wordwrap() example


<?php
$text
= "The quick brown fox jumped over the lazy dog.";
$newtext = wordwrap($text, 20, "<br />n");

echo

$newtext;
?>

The above example will output:

The quick brown fox<br />
jumped over the lazy<br />
dog.

Example #2 wordwrap() example


<?php
$text
= "A very long woooooooooooord.";
$newtext = wordwrap($text, 8, "n", true);

echo

"$newtextn";
?>

The above example will output:

A very
long
wooooooo
ooooord.

Example #3 wordwrap() example


<?php
$text
= "A very long woooooooooooooooooord. and something";
$newtext = wordwrap($text, 8, "n", false);

echo

"$newtextn";
?>

The above example will output:

A very
long
woooooooooooooooooord.
and
something

See Also

  • nl2br() — Inserts HTML line breaks before all newlines in a string
  • chunk_split() — Split a string into smaller chunks

Alhadis

8 years ago


For those interested in wrapping text to fit a width in *pixels* (instead of characters), you might find the following function useful; particularly for line-wrapping text over dynamically-generated images.

If a word is too long to squeeze into the available space, it'll hyphenate it as needed so it fits the container. This operates recursively, so ridiculously long words or names (e.g., URLs or this guy's signature - http://en.wikipedia.org/wiki/Wolfe+585,_Senior) will still keep getting broken off after they've passed the fourth or fifth lines, or whatever.

<?php/**
     * Wraps a string to a given number of pixels.
     *
     * This function operates in a similar fashion as PHP's native wordwrap function; however,
     * it calculates wrapping based on font and point-size, rather than character count. This
     * can generate more even wrapping for sentences with a consider number of thin characters.
     *
     * @static $mult;
     * @param string $text - Input string.
     * @param float $width - Width, in pixels, of the text's wrapping area.
     * @param float $size - Size of the font, expressed in pixels.
     * @param string $font - Path to the typeface to measure the text with.
     * @return string The original string with line-breaks manually inserted at detected wrapping points.
     */
   
function pixel_word_wrap($text, $width, $size, $font){#    Passed a blank value? Bail early.
       
if(!$text) return $text;#    Check if imagettfbbox is expecting font-size to be declared in points or pixels.
       
static $mult;
       
$mult    =    $mult ?: version_compare(GD_VERSION, '2.0', '>=') ? .75 : 1;#    Text already fits the designated space without wrapping.
       
$box    =    imagettfbbox($size * $mult, 0, $font, $text);
        if(
$box[2] - $box[0] / $mult < $width)    return $text;#    Start measuring each line of our input and inject line-breaks when overflow's detected.
       
$output        =    '';
       
$length        =    0;$words        =    preg_split('/b(?=S)|(?=s)/', $text);
       
$word_count    =    count($words);
        for(
$i = 0; $i < $word_count; ++$i){#    Newline
           
if(PHP_EOL === $words[$i])
               
$length    =    0;#    Strip any leading tabs.
           
if(!$length) $words[$i]    =    preg_replace('/^t+/', '', $words[$i]);$box    =    imagettfbbox($size * $mult, 0, $font, $words[$i]);
           
$m        =    $box[2] - $box[0] / $mult;#    This is one honkin' long word, so try to hyphenate it.
           
if(($diff = $width - $m) <= 0){
               
$diff    =    abs($diff);#    Figure out which end of the word to start measuring from. Saves a few extra cycles in an already heavy-duty function.
               
if($diff - $width <= 0)    for($s = strlen($words[$i]); $s; --$s){
                   
$box    =    imagettfbbox($size * $mult, 0, $font, substr($words[$i], 0, $s) . '-');
                    if(
$width > ($box[2] - $box[0] / $mult) + $size){
                       
$breakpoint    =    $s;
                        break;
                    }
                }

                else{

$word_length    =    strlen($words[$i]);
                    for(
$s = 0; $s < $word_length; ++$s){
                       
$box    =    imagettfbbox($size * $mult, 0, $font, substr($words[$i], 0, $s+1) . '-');
                        if(
$width < ($box[2] - $box[0] / $mult) + $size){
                           
$breakpoint    =    $s;
                            break;
                        }
                    }
                }

                if(

$breakpoint){
                   
$w_l    =    substr($words[$i], 0, $s+1) . '-';
                   
$w_r    =    substr($words[$i],     $s+1);$words[$i]    =    $w_l;
                   
array_splice($words, $i+1, 0, $w_r);
                    ++
$word_count;
                   
$box    =    imagettfbbox($size * $mult, 0, $font, $w_l);
                   
$m        =    $box[2] - $box[0] / $mult;
                }
            }
#    If there's no more room on the current line to fit the next word, start a new line.
           
if($length > 0 && $length + $m >= $width){
               
$output    .=    PHP_EOL;
               
$length    =    0;#    If the current word is just a space, don't bother. Skip (saves a weird-looking gap in the text).
               
if(' ' === $words[$i]) continue;
            }
#    Write another word and increase the total length of the current line.
           
$output    .=    $words[$i];
           
$length +=    $m;
        }

        return

$output;
    };
?>


ju1ius

11 years ago


Another solution to utf-8 safe wordwrap, unsing regular expressions.
Pretty good performance and works in linear time.

<?php
function utf8_wordwrap($string, $width=75, $break="n", $cut=false)
{
  if(
$cut) {
   
// Match anything 1 to $width chars long followed by whitespace or EOS,
    // otherwise match anything $width chars long
   
$search = '/(.{1,'.$width.'})(?:s|$)|(.{'.$width.'})/uS';
   
$replace = '$1$2'.$break;
  } else {
   
// Anchor the beginning of the pattern with a lookahead
    // to avoid crazy backtracking when words are longer than $width
   
$pattern = '/(?=s)(.{1,'.$width.'})(?:s|$)/uS';
   
$replace = '$1'.$break;
  }
  return
preg_replace($search, $replace, $string);
}
?>
Of course don't forget to use preg_quote on the $width and $break parameters if they come from untrusted input.


Dave Lozier — dave at fusionbb.com

17 years ago


If you'd like to break long strings of text but avoid breaking html you may find this useful. It seems to be working for me, hope it works for you. Enjoy. :)

<?php

   
function textWrap($text) {

       
$new_text = '';

       
$text_1 = explode('>',$text);

       
$sizeof = sizeof($text_1);

        for (
$i=0; $i<$sizeof; ++$i) {

           
$text_2 = explode('<',$text_1[$i]);

            if (!empty(
$text_2[0])) {

               
$new_text .= preg_replace('#([^nr .]{25})#i', '\1  ', $text_2[0]);

            }

            if (!empty(
$text_2[1])) {

               
$new_text .= '<' . $text_2[1] . '>';   

            }

        }

        return
$new_text;

    }

?>


michdingpayc

9 months ago


A correction to ju1ius' utf-8 safe wordwrap from 10 years ago.
This version addresses issues where breaks were not being added to the first and last words in the input string.

<?php
function utf8_wordwrap($string, $width=75, $break="n", $cut=false)
{
  if(
$cut) {
   
// Match anything 1 to $width chars long followed by whitespace,
    // otherwise match anything $width chars long
   
$search= '/(.{1,'.$width.'})(?:s)|(.{'.$width.'})(?!$)/uS';
   
$replace = '$1$2'.$break;
  } else {
   
// Anchor the beginning of the pattern with a lookbehind
    // to avoid crazy backtracking when words are longer than $width
   
$search= '/(?<=s|^)(.{1,'.$width.'}S*)(?:s)/uS';
   
$replace = '$1'.$break;
  }
  return
preg_replace($search, $replace, $string);
}
?>


frans-jan at van-steenbeek dot R-E-M-O-V-E dot net

17 years ago


Using wordwrap is usefull for formatting email-messages, but it has a disadvantage: line-breaks are often treated as whitespaces, resulting in odd behaviour including lines wrapped after just one word.

To work around it I use this:

<?php
function linewrap($string, $width, $break, $cut) {
 
$array = explode("n", $string);
 
$string = "";
  foreach(
$array as $key => $val) {
  
$string .= wordwrap($val, $width, $break, $cut);
  
$string .= "n";
  }
  return
$string;
}
?>

I then use linewrap() instead of wordwrap()

hope this helps someone


php at maranelda dot org

14 years ago


Anyone attempting to write a text email client should be aware of the following:

<?php

$a

= "some text that must wrap nice";$a = wordwrap($a, 9);

echo

$a;//  some text
//  that must
//  wrap nice
$a = wordwrap($a, 9);

echo

$a;//  some text
//  that
//  must
//  wrap
//  nice
?>

Subsequent uses of wordwrap() on already wrapped text will take the end-of-line characters into account when working out line length, thus reading each line that just fit nicely the first time around as being one character too long the second. This can be a problem when preparing a text email that contains (eg.) a forwarded email which has already been word-wrapped.

Solutions below which explode() the text on end-of-lines and wordwrap() the resulting strings separately take care of this nicely.


Peter

16 years ago


The main concern when you have a text in a cell is for long words that drags the cell margins. This function will break words in a text that have more then $nr characters using the "-" char.

<?php

function processtext($text,$nr=10)

    {

       
$mytext=explode(" ",trim($text));

       
$newtext=array();

        foreach(
$mytext as $k=>$txt)

        {

            if (
strlen($txt)>$nr)

            {

               
$txt=wordwrap($txt, $nr, "-", 1);

            }

           
$newtext[]=$txt;

        }

        return
implode(" ",$newtext);

    }

?>


info at hsdn dot org

11 years ago


Wordwrap with UTF-8 supports, returns as array.

<?phpfunction mb_wordwrap_array($string, $width)
{
    if ((
$len = mb_strlen($string, 'UTF-8')) <= $width)
    {
        return array(
$string);
    }
$return = array();
   
$last_space = FALSE;
   
$i = 0;

    do
    {
        if (

mb_substr($string, $i, 1, 'UTF-8') == ' ')
        {
           
$last_space = $i;
        }

        if (

$i > $width)
        {
           
$last_space = ($last_space == 0) ? $width : $last_space;$return[] = trim(mb_substr($string, 0, $last_space, 'UTF-8'));
           
$string = mb_substr($string, $last_space, $len, 'UTF-8');
           
$len = mb_strlen($string, 'UTF-8');
           
$i = 0;
        }
$i++;
    }
    while (
$i < $len);$return[] = trim($string);

    return

$return;
}
?>


altin_bardhi at yahoo dot co dot uk

12 years ago


Here I have come out with a possibly very useful wordwrap code snippet.

Apparently what this piece of code does is: it takes the entered text and looks for words longer than the defined ‘$chunk_length’ if it finds any, it splits the long words and then it concatenates the whole string back to a new string with longer words separated by a dash character in this case.

After it has accomplished this task it then inserts an HTML line break after a specified ‘$line_length’ (Depending on your containers width requirements)

<?php//Start function explode_ wrap
function explode_wrap($text, $chunk_length, $line_length){//Explode all the words separated by spaces in a string
$string_chunks = explode(' ', $text);// Get each split word from the array $sring_chunks_array => key => value
foreach ($string_chunks as $chunk => $value) {

if(

strlen($value) >= $chunk_length){//Split the chunks/words which are longer than $chunk_length
$new_string_chunks[$chunk] = chunk_split($value, $chunk_length, ' - ');

}else {

//Do not split the normal length words
$new_string_chunks[$chunk] = $value;

}

}

//End foreach loop

//Concatenate back the all the words

$new_text=implode(' ', $new_string_chunks);

return

wordwrap($new_text, $line_length, '<br />');

}

//End function?>


$del=’ at ‘; ‘sanneschaap’ dot $del dot ‘gmail dot com’

14 years ago


These functions let you wrap strings comparing to their actual displaying width of proportional font. In this case Arial, 11px. Very handy in some cases since CSS3 is not yet completely supported. 100 strings = ~5 ms

My old sheep word wrap function (posted at the bottom of this page, is kinda old dated and this one is faster and more accurate).

<?php

//the width of the biggest char @

$fontwidth = 11;
//each chargroup has char-ords that have the same proportional displaying width

$chargroup[0] = array(64);

$chargroup[1] = array(37,87,119);

$chargroup[2] = array(65,71,77,79,81,86,89,109);

$chargroup[3] = array(38,66,67,68,72,75,78,82,83,85,88,90);

$chargroup[4] = array(35,36,43,48,49,50,51,52,53,54,55,56,57,60,61,62,63, 69,70,76,80,84,95,97,98,99,100,101,103,104,110,111,112, 113,115,117,118,120,121,122,126);

$chargroup[5] = array(74,94,107);

$chargroup[6] = array(34,40,41,42,45,96,102,114,123,125);

$chargroup[7] = array(44,46,47,58,59,91,92,93,116);

$chargroup[8] = array(33,39,73,105,106,108,124);
//how the displaying width are compared to the biggest char width

$chargroup_relwidth[0] = 1; //is char @

$chargroup_relwidth[1] = 0.909413854;

$chargroup_relwidth[2] = 0.728241563;

$chargroup_relwidth[3] = 0.637655417;

$chargroup_relwidth[4] = 0.547069272;

$chargroup_relwidth[5] = 0.456483126;

$chargroup_relwidth[6] = 0.36589698;

$chargroup_relwidth[7] = 0.275310835;

$chargroup_relwidth[8] = 0.184724689;
//build fast array

$char_relwidth = null;

for (
$i=0;$i<count($chargroup);$i++){

    for (
$j=0;$j<count($chargroup[$i]);$j++){

       
$char_relwidth[$chargroup[$i][$j]] = $chargroup_relwidth[$i];

    }

}
//get the display width (in pixels) of a string

function get_str_width($str){

    global
$fontwidth,$char_relwidth;

   
$result = 0;

    for (
$i=0;$i<strlen($str);$i++){

       
$result += $char_relwidth[ord($str[$i])];

    }

   
$result = $result * $fontwidth;

    return
$result;   

}
//truncates a string at a certain displaying pixel width

function truncate_str_at_width($str, $width, $trunstr='...'){

    global
$fontwidth,$char_relwidth;       

   
$trunstr_width = get_str_width($trunstr);

   
$width -= $trunstr_width;

   
$width = $width/$fontwidth;

   
$w = 0;

    for (
$i=0;$i<strlen($str);$i++){

       
$w += $char_relwidth[ord($str[$i])];

        if (
$w > $width)

            break;   

    }

   
$result = substr($str,0,$i).$trunstr;

    return
$result;

   
// texas is the reason rules at 10am :)

}

?>


Marcin Dobruk [zuku3000 at yahoo dot co dot uk]

13 years ago


Word wrap from left to right (standard) and from right to left.

<?php

function myWordWrap ($string, $length=3, $wrap=',', $from='left') {

    if (
$from=='left') $txt=wordwrap($string, $length, $wrap, true);

    if (
$from=='right') {

       
// string to array

       
$arr_l=array();

        for (
$a=0;strlen($string)>$a;$a++) $arr_l[$a]=$string{$a};

       
// reverse array

       
$arr_r=array_reverse($arr_l);

       
// array to string

       
$string_r='';

        foreach (
$arr_r as $arr_line => $arr) $string_r.=$arr;

       
// add wrap to reverse string

       
$string_r=wordwrap($string_r, $length, $wrap, true);

       
// reverse string to array

       
$arr_r=array();

        for (
$a=0;strlen($string_r)>$a;$a++) $arr_r[]=$string_r{$a};

       
// reverse array again

       
$arr_l=array_reverse($arr_r);

       
// string with wrap

       
$txt='';

        foreach (
$arr_l as $arr_line => $arr) $txt.=$arr;

        }

    return
$txt;

    }

?>


ojs-hp at web dot de

13 years ago


After I got some problems with my function to convert a BB-text into HTML. Long words didn't really fit into the layout and only wordwarp() also added breaks to words which would fit into the layout or destroy the other HTML-tags....
So this is my solution. Only words with strlen() >= 40 are edited with wordwarp().

<?php
function bb2html($bb) {
       
$words= explode(' ', $bb); // string to array
   
foreach ($words as $word) {
       
$break = 0;
        for (
$i = 0; $i < strlen($word); $i++) {
            if (
$break >= 40) {
               
$word= wordwrap($word, 40, '-<br>', true); //add <br> every 40 chars
               
$break = 0;
            }
           
$break++;

        }

$newText[] = $word; //add word to array
   
}
   
$bb = implode(' ', $newText); //array to string
   
return $bb;
}
?>


maikuolan at gmail dot com

10 years ago


(Re: kouber at php dot net).

Testing out your function, I can confirm that it works, and it works very well.

However, others that intend to use your function need to be aware that if they use it in conjunction with unverified data (such as raw user input from $_POST, $_GET, etcetera), they are creating potential attack vectors that can be exploited by hackers via script requests containing malicious code. This is because your function is using the preg_replace function in conjunction with the "e" flag (in order to allow the chunk_split bit to execute), which can allow execution of arbitrary code.

Solution: If there is any possibility that $str may contain unverified data (such as raw user input), ensure that the contents of $str is sanitized (such as by using htmlentities/htmlspecialchars/etc) prior to sending it to wrap($str,...).

Not a criticism; I intend to use your function, because I like it. However, just posting this as a note to other users that may not be aware of the importance of data sanitation.


kozimbek at mail dot ru

7 years ago


After searching and being tired of many non-working mb_wordwrap functions at many places, I finally created a really simple and working solution

<?php
function mb_wordwrap($string, $limit)
{
   
$string = strip_tags($string); //Strip HTML tags off the text
   
$string = html_entity_decode($string); //Convert HTML special chars into normal text
   
$string = str_replace(array("r", "n"), "", $string); //Also cut line breaks
   
if(mb_strlen($string, "UTF-8") <= $limit) return $string; //If input string's length is no more than cut length, return untouched
   
$last_space = mb_strrpos(mb_substr($string, 0, $limit, "UTF-8"), " ", 0, "UTF-8"); //Find the last space symbol positionreturn mb_substr($string, 0, $last_space, "UTF-8").' ...'; //Return the string's length substracted till the last space and add three points
}
?>

The function simply searches the last space symbol in the range and returns the string cut till that position. No iterations, no regular expressions and no buffer overload. Tested with large Russian texts and works perfectly.


phil_marmotte at yahoo dot fr

8 years ago


Another Word wrap from left or right :

public static function myWordWrap ($string, $length=3, $wrap=',', $from='left') {
        if ($from=='left') $txt=wordwrap($string, $length, $wrap, true);
            if ($from=='right') {
                $m = strlen($string)%$length;
                if ($m < strlen($string))
                    $txt = substr($string,0,$m).$wrap.wordwrap(substr($string,$m),$length, $wrap, true);
                else
                    $txt = $string;
            }

            return $txt;
       }


joachim

14 years ago


There seems to be a difference between php 5.1 and 5.2 in how wordwrap counts characters (all on Mac OSX 10.5.2):

/Applications/MAMP/bin/php5/bin/php --version
PHP 5.1.6 (cli) (built: Sep  8 2006 10:25:04)

/Applications/MAMP/bin/php5/bin/php -r 'echo wordwrap("In aller Freundschaft (50)_UT", 20) . "n";'
In aller
Freundschaft
(50)_UT

php --version
PHP 5.2.5 (cli) (built: Feb 20 2008 12:30:47)

php -r 'echo wordwrap("In aller Freundschaft (50)_UT", 20) . "n";'
In aller
Freundschaft (50)_UT


answers at clearcrescendo.com

3 years ago


wordwrap() uses the break string as the line break detected, and the break inserted, so your text must be standardized to the line break you want in the wordwrap() output before using wordwrap, otherwise you will get line breaks inserted regardless of the location of existing line breaks in your text.

<?php
    $linebreak
= '<br/>' . PHP_EOL;
   
$width = 5;
   
$standardized = preg_replace('/r?n/',$linebreak, "abc abc abcnabc abc abcrnabc abc abc");
    echo
'Standardized EOL:', PHP_EOL, $standardized, PHP_EOL, PHP_EOL; // PHP_EOL for the command line, use '<br/>' for HTML.
   
echo "Wrapped at $width:", PHP_EOL, wordwrap( $standardized, 7, $linebreak), PHP_EOL;
?>

$ php -f test.php
Standardized EOL:
abc abc abc<br/>
abc abc abc<br/>
abc abc abc

Wrapped at 5:
abc abc<br/>
abc<br/>
abc abc<br/>
abc<br/>
abc abc<br/>
abc


tuxedobob

5 years ago


It should be noted that the behavior of the $break parameter is poorly explained.

If you specify the $break parameter, then *that string defines what the function considers a "newline"*.

Consider the following string:

$str = "Rumplestiltskin Schwartzmenikoff
1534 Gingerbread Lane
Black Forest, Germany";

You are trying to fit this address into a space that only allows for 22 characters, but you want it clear that you're continuing a previous line, so you want a space added. You might try this:

$str = wordwrap($str, 22, "n>");

If you did that, you would end up with the following output:

"Rumplestiltskin
>Schwartzmenikoff
1534
>Gingerbread Lane
Black
>Forest, Germany"

This is because when you pass it a third parameter of "n>", it assumes that entire string is a newline character. It's no longer using "n". In your output, of course, n is still a newline, so it appears to have extra lines.

If you're looking to wordwrap a multi-line string with something besides a newline character, make sure all existing linebreaks are already delineated with the string you pass to wordwrap().


zac dot hester at gmail dot com

8 years ago


I recently ran into the issue discussed by another contributor to this function (frans-jan at van-steenbeek dot R-E-M-O-V-E dot net).  The problem appeared to be how wordwrap() was treating white space.  Instead of writing my own version of wordwrap(), I discovered that the "break" parameter is not only used as the inserted string, but also used to detect the existing wrap delimiters (e.g. line endings).  If you can manage to "normalize" the wrap delimiters in your original string, you don't need to try to work-around the function wrapping at seemingly odd places (like immediately after one short word).  As one quick-and-dirty way to get wordwrap() to play nicely with most use-cases, I did this:

<?php
$break
= strpos( $content, "r" ) === false ? "n" : "rn";
$content = wordwrap( $content, 78, $break );
?>

I also tend to normalize multi-line strings (if my OCD is acting up).  You would typically perform this conversion _before_ sending it off to wordwrap().

<?php
//quick and simple, but clobbers old-style Mac line-endings
$content = str_replace( "r", '', $content );//slower, but works with everything
$content = preg_replace( "/(rn|r)/", "n", $content );//now, wordwrap() will behave exactly as expected
$content = wordwrap( $content, 78, "n" );
?>


bruceboughton @ google mail

17 years ago


I found that wordwrap deletes the spaces it wraps on. If you want to break up a string which doesn't consist of words, you may find this behaviour undesirable, as I did when trying to wordwrap a Regular Expression to 80 characters (for display along with test string, matches, etc.).

To preserve the spaces and still achieve a consistent cut length, you need to replace spaces with a suitable one-character replacement. I chose the ASCII non-printing character SUB (ASCII #26; some old telephone code meaning substitute):

<?php
$regex
= str_replace(' ', chr(26), $regex);
$regex= wordwrap($regex, 80, '<br />', TRUE);
$regex= str_replace(chr(26), ' ', $regex);
?>

(Of course, you need to replace 80 with your column length and '<br />' with your break string)


nbenitezl[arroba]gmail[dot]com

12 years ago


Hi, this function is like wordwrap but it ignores html tags, it works like wordwrap when called with fourth parameter as true. It's based on a function I find here but improved to closer match the output of wordwrap (i.e. removed spaces at start of line) and also to improve performance.

Hope it can be useful for you :-)
<?php
function htmlwrap(&$str, $maxLength, $char='<br />'){
   
$count = 0;
   
$newStr = '';
   
$openTag = false;
   
$lenstr = strlen($str);
    for(
$i=0; $i<$lenstr; $i++){
       
$newStr .= $str{$i};
        if(
$str{$i} == '<'){
           
$openTag = true;
            continue;
        }
        if((
$openTag) && ($str{$i} == '>')){
           
$openTag = false;
            continue;
        }
        if(!
$openTag){
            if(
$str{$i} == ' '){
                if (
$count == 0) {
                   
$newStr = substr($newStr,0, -1);
                    continue;
                } else {
                   
$lastspace = $count + 1;
                }
            }
           
$count++;
            if(
$count==$maxLength){
                if (
$str{$i+1} != ' ' && $lastspace && ($lastspace < $count)) {
                   
$tmp = ($count - $lastspace)* -1;
                   
$newStr = substr($newStr,0, $tmp) . $char . substr($newStr,$tmp);
                   
$count = $tmp * -1;
                } else {
                   
$newStr .= $char;
                   
$count = 0;
                }
               
$lastspace = 0;
            }
        } 
    }

    return

$newStr;
}
?>


Matt at newbiewebdevelopment dot idk

14 years ago


My version of multibyte wordwrap

<?php
function mb_wordwrap($string, $width=75, $break="n", $cut = false) {
    if (!
$cut) {
       
$regexp = '#^(?:[x00-x7F]|[xC0-xFF][x80-xBF]+){'.$width.',}b#U';
    } else {
       
$regexp = '#^(?:[x00-x7F]|[xC0-xFF][x80-xBF]+){'.$width.'}#';
    }
   
$string_length = mb_strlen($string,'UTF-8');
   
$cut_length = ceil($string_length / $width);
   
$i = 1;
   
$return = '';
    while (
$i < $cut_length) {
       
preg_match($regexp, $string,$matches);
       
$new_string = $matches[0];
       
$return .= $new_string.$break;
       
$string = substr($string, strlen($new_string));
       
$i++;
    }
    return
$return.$string;
}
$mb_string = "こんにちは";//Hello in Japanese
$cut_mb_string = mb_wordwrap($mb_string,1," ",true); //こ ん に ち は
print($cut_mb_string);
?>


simbiat at bk dot ru

6 years ago


Some people use wordwrap as long text cutter. I have a slightly different approach for that. The function does not wrap the text, but returns the position where to cut. It preserves HTML tags (does not count them) and strips br tags and whitespaces at the end. I am looking into a way prevent HTML tags corruption which can happen at this time and also support BB tags like code and quote, so that they won't be counted as well. When I do, I'll post an updated version of the code.

<?php
function txtcut($string, $length) {
   
$tag = false;
   
$chars = 0;
   
$position = 0;
   
$split = str_split($string);
    foreach (
$split as $char) {
       
$position++;
        if (
$char == "<") {
           
$tag = true;
            continue;
        }
        if (
$char == ">") {
           
$tag = false;
            continue;
        }
        if (
$tag == true) {
            continue;
        }
       
$chars++;
        if (
$chars >= $length) {
            if (
$char == " " || $char == "r" || $char == "n") {
               
$position--;
                break;
            }
        }
    }
    if (
$position == strlen($string)) {
        return
strlen($string);
    } else {
       
$string = substr($string, 0, $position);
        if (
substr($string, -4, 4) == "<br>") {
           
$string = rtrim(substr($string, 0, -4));
        }
        return
strlen($string);
    }
}
?>


Понравилась статья? Поделить с друзьями:
  • Code for date in excel
  • Collection contains vba excel
  • Collecting data from word forms
  • Collect word from letters
  • Collect data in excel