Page 1 of 1

How to do word wrapping using php

Posted: Fri Jul 15, 2011 6:38 pm
by Saman
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; 
 
    } 
 
?>