• Skip to main content
  • Skip to primary sidebar
  • Skip to footer

Matt Doyle | Elated Communications

Web and WordPress Development

  • About Me
  • Blog
    • Design & Multimedia
      • Photoshop
      • Paint Shop Pro
      • Video & Audio
    • Online Marketing
      • E-Commerce
      • Social Media
    • Running a Website
      • WordPress
      • Apache
      • UNIX and Linux
      • Using FTP
    • Web Development
      • HTML
      • CSS
      • JavaScript
      • PHP
      • Perl and CGI Scripting
  • Portfolio
  • Contact Me
  • Hire Me
Home / Blog / Web Development / PHP / PHP Strings / Wrapping Text with PHP’s wordwrap() Function

Wrapping Text with PHP’s wordwrap() Function

19 January 2010 / 5 Comments

Occasionally your PHP script will need to break up a long line of text into several shorter lines while preserving whole words. This can happen if you’re formatting some text for printing or emailing, or you want to display preformatted text in a Web page using the pre element.

PHP gives you a handy function, wordwrap(), to do this job for you. This tutorial shows you how wordwrap() works.

Basic wordwrap() syntax

In its most basic form, you just pass a string to wordwrap(), and it returns the wrapped string:


$myString = "Mr. Bennet was so odd a mixture of quick parts, sarcastic humour, reserve, and caprice, that the experience of three-and-twenty years had been insufficient to make his wife understand his character.";
echo "<pre>" . wordwrap( $myString ) . "</pre>";

The above code displays:


Mr. Bennet was so odd a mixture of quick parts, sarcastic humour, reserve,
and caprice, that the experience of three-and-twenty years had been
insufficient to make his wife understand his character.

By default, wordwrap() uses a column width of 75 characters. This means that no line will be more than 75 characters long.

Specifying the column width

To specify a column width other than 75 characters, pass the width as the second argument to wordwrap():


$myString = "Mr. Bennet was so odd a mixture of quick parts, sarcastic humour, reserve, and caprice, that the experience of three-and-twenty years had been insufficient to make his wife understand his character.";
echo "<pre>" . wordwrap( $myString, 40 ) . "</pre>";

Mr. Bennet was so odd a mixture of quick
parts, sarcastic humour, reserve, and
caprice, that the experience of
three-and-twenty years had been
insufficient to make his wife understand
his character.

Using different line break characters

Normally, wordwrap() breaks text into lines by inserting a newline ("n") character at the end of each line. However, you can specify your own line break character (or string of characters) as the third argument to wordwrap().

For example, if you’re outputting the result to a Web page, and you’re not using the pre element to display preformatted text, then you can break the lines using the HTML line break element, <br />:


$myString = "Mr. Bennet was so odd a mixture of quick parts, sarcastic humour, reserve, and caprice, that the experience of three-and-twenty years had been insufficient to make his wife understand his character.";
echo wordwrap( $myString, 40, "<br />" );

Wrapping very long words

What happens if the text contains a word that is longer than the desired column width? By default, this results in a line that is longer than the column width:


myString = "This text contains a very very loooooooooooooooooooong word.";
echo "<pre>" . wordwrap( $myString, 10 ) . "</pre>";

This text
contains a
very very
loooooooooooooooooooong
word.

To prevent this happening, pass true as the fourth argument to wordwrap(). This breaks any words that are longer than the specified column width:


myString = "This text contains a very very loooooooooooooooooooong word.";
echo "<pre>" . wordwrap( $myString, 10, "n", true ) . "</pre>";

This text
contains a
very very
looooooooo
oooooooooo
ong word.

In this article you learned how to use PHP’s wordwrap() function to split strings of text over several lines. You saw how to specify the maximum line length, how to use different characters to break up the lines of text, and how to deal with very long words.

Happy coding!

Filed Under: PHP Strings Tagged With: column width, line break characters, line length, long words, php wordwrap, wrapping text

Reader Interactions

Comments

  1. Takunda Madzamba says

    16 October 2019 at 2:51 am

    Hi MATT

    This is a smarter way to do wrap.

    How do i come up with my own word wrap function without using wordwrap?

    Reply
    • Matt Doyle says

      22 October 2019 at 1:07 am

      Hi Takunda, why would you want to do that?

      Reply
      • Daniel says

        5 December 2022 at 12:56 pm

        For example to introduce custom handling of characters other than space, for example period, coma, hyphens etc.

        Reply
  2. Сергей says

    20 May 2020 at 5:25 pm

    Привет Мэтт Спасибо ознакомление с функцией wordwrap не плохое познание мне понравился урок мое хобби можит когда небудь мне принесет удовлитворение и я наконец не буду стоять перед вратами а зайду в дверь хотя время бежит скоротечьно и в мое время как вы молоды был один трактор и незнали тогда что такое Компьютер и как это клас познать мир

    Reply
  3. Mazz says

    7 June 2020 at 4:15 pm

    Hi .. Thanks …Very useful … And this in 2020 too …

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

To include a block of code in your comment, surround it with <pre> ... </pre> tags. You can include smaller code snippets inside some normal text by surrounding them with <code> ... </code> tags.

Allowed tags in comments: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre> .

Primary Sidebar

Hire Matt!

Matt Doyle headshot

Need a little help with your website? I have over 20 years of web development experience under my belt. Let’s chat!

Matt Doyle - Codeable Expert Certificate

Hire Me Today

Call Me: +61 2 8006 0622

Stay in Touch!

Subscribe to get a quick email whenever I add new articles, free goodies, or special offers. I won’t spam you.

Subscribe

Recent Posts

  • Make a Rotatable 3D Product Boxshot with Three.js
  • Speed Up Your WordPress Website: 11 Simple Steps to a Faster Site
  • Reboot!
  • Wordfence Tutorial: How to Keep Your WordPress Site Safe from Hackers
  • How to Make Awesome-Looking Images for Your Website

Footer

Contact Matt

  • Email Me
  • Call Me: +61 2 8006 0622

Follow Matt

  • E-mail
  • Facebook
  • GitHub
  • LinkedIn
  • Twitter

Copyright © 1996-2023 Elated Communications. All rights reserved.
Affiliate Disclaimer | Privacy Policy | Terms of Use | Service T&C | Credits