How to do word wrapping using php

Post Reply
User avatar
Saman
Lieutenant Colonel
Lieutenant Colonel
Posts: 828
Joined: Fri Jul 31, 2009 10:32 pm
Location: Mount Lavinia

How to do word wrapping using php

Post by Saman » Fri Jul 15, 2011 6:38 pm

A function that takes a string of text and wraps it into lines of a length that you determine. Can be useful for guestbooks, news posting scripts etc. to prevent the layout breaking.

Code: Select all

<?php 
 
/** 
 * Example usage: 
 *  
 * // Your text 
 * $text = "This is a sentence which contains some words."; 
 *  
 * // Or from a database result 
 * $text = $row['text']; 
 *  
 * // Then put it into the function 
 * $text = word_wrap($text); 
 *  
 * // Output the result 
 * echo $text; 
 */ 
 
    function word_wrap($text) { 
 
        // Define the characters to display per row 
        $chars = "10"; 
 
        $text = wordwrap($text, $chars, "<br />", 1); 
 
        return $text; 
 
    } 
 
?>
Post Reply

Return to “PHP & MySQL”