PHP's wordwrap() Function to Handle Long Text


When managing user generated content on websites, long usernames or posts can mess up your layout. One way to limit text input is by setting constraints in your HTML form:

PHP Code
  1. <input type="text" name="user" size="15" maxlength="20">

  • size: Defines how wide the input box appears.
  • maxlength: Specifies the maximum number of characters allowed.


But what if the content is already submitted and too long? PHP's wordwrap() function is here to help.



Using wordwrap() to Wrap Long Strings


The wordwrap() function in PHP wraps long strings into smaller chunks, adding line breaks to prevent layout issues. Here's an example:

PHP Code
  1. <?php
  2. $string = "This is an example of a really really really long post that may stretch your page a few inches or pixels and make the layout look like crap"; // A demo string
  3.  
  4. $wrap = wordwrap($string, 15, "n"); // Wrap the text at 15 characters per line
  5.  
  6. echo $wrap; // Output the wrapped text
  7. ?>


The output of this script will look like this:


This is an
example of a
really really
really long
post that may
stretch your
page a few
inches or
pixels and make
the layout look
like crap





Understanding the wordwrap() Function


The syntax for wordwrap() is as follows:

PHP Code
  1. wordwrap(string $string, int $length = 75, string $break = "n", bool $cut = false): string


  • $string: The text you want to wrap.
  • $length (Optional): Specifies the maximum line length. The default is "75".
  • $break (Optional): Defines the string used for line breaks. The default is "n".
  • $cut (Optional): If true, words are split when they exceed the specified length. If false, words are kept intact and wrapped at spaces.




Optional Parameters in wordwrap()


You can adjust the behavior of wordwrap() using optional parameters:

Custom Break Character: Use any string for the line break. For example:
PHP Code
  1. $wrap = wordwrap($string, 15, " | ");


Force Word Splitting: To split words that exceed the length, set the "cut" parameter to "true":
PHP Code
  1. $wrap = wordwrap($string, 15, "n", true);



Conclusion


The wordwrap() function is a simple and effective way to handle long strings, ensuring they don't disrupt your layout. Use it alongside input constraints in forms for a seamless and user friendly design.
Play around with its optional parameters to tailor it to your needs!
ShadowMage's Avatar
Author:
Views:
2,221
Rating:
There are currently no comments for this tutorial, login or register to leave one.