Wednesday, July 6, 2011

php wrap lines

PHP's wordwrap() function probably can serve well. But this function will even put paragraphs into one line. We want to wrap our lines based on the given width number, but we also want to make sure that a paragraph starts from a new line and we might also want to do indention.

The logic is below.

1. we want to break the text into paragraphs. This can be done by
$paragraphs = explode("\n", $text);

2. For each paragraph, we break the it into words.
$words = explode(" ", $paragraph);
We also want to indent for each new paragraph: str_repeat(" ", $indent);

3. For each word, we check if (the length of current line + word length) > $width, if yes, then put the word at the same line; if no, put the word at the next line.

Based on the logic, we can have our own wrapping function

function myWordwrap($text, $width, $indent, $break="\n")
{
   //initialize $wrappedText, which will store the wrapped text
   $wrappedText = "";
   
   //break the text into paragraphs
   $paragraphs = explode("\n", $text);
   foreach($paragraphs as $paragraph)
   {
      //if we do indent, prefix with space
      if ($indent > 0) {
         $wrappedText .= str_repeat(" ", $indent);
      }
      
      //break a paragraph into words
      $words      = explode(" ", $paragraph);
      $lineLength = $indent;
      foreach($words as $word)
      {
       //get the word length
         $wordLength = strlen($word);
 
         //the current line length cannot be larger than the given width
         if (($lineLength + $wordLength ) < $width)
         {
            $wrappedText .= $word . ' ';
            $lineLength  += $wordLength + 1;
         } else {
            //we have to put the word in a new line
            $wrappedText  = trim($wrappedText);
            $wrappedText .= $break . $word . ' ';
            //update length
            $lineLength = $wordLength;
         }
      }

      $wrappedText  = trim($wrappedText);
      //one paragraph ends, start a new line
      $wrappedText .= $break;
   }

   return $wrappedText;
}

No comments: