Jump to content

[SOLVED] Wordwrap Text


deecee2000

Recommended Posts

Hi All,

 

  I was looking some help to wrap my current text.

 

  $text = "This is First Test."

 

  I want to wrap this above text and expect below output.

  If I wrap by 3 characters then,

 

  Expected Output:

  Thi-

  s is

  Fir-

  st

  Tes-

  t.

 

  So let say if the word's character length is more than 3 characters than it will add "-" (Hyphen) and split the remaining characters in to next line.

 

  Any help will be appreciated.

Thanks,

 

 

 

 

Link to comment
https://forums.phpfreaks.com/topic/181754-solved-wordwrap-text/
Share on other sites

Hey Rajiv,

 

  Thnx for quick response. I tried...

 

  $text = "This is First Test.";

  $newtext = wordwrap($text, 3, "-<br />\n", true);

 

  And the output is..

  Thi-

  s-

  is-

  Fir-

  st-

  Tes-

  t.-

 

  So it not seems like expected output.

 

Thanks,

Link to comment
https://forums.phpfreaks.com/topic/181754-solved-wordwrap-text/#findComment-958608
Share on other sites

I think something like this should do it:

function wordwrap2($text, $maxLength, $separator = '-')
{
    $lines = explode("\n", $text);
    $linesNew = array();
    foreach ($lines as $line) {
        $length = strlen($line);
        if ($length > $maxLength) {
            $start = substr($line, 0, $maxLength);
            if (strlen($start) != strlen(rtrim($start))) {
                $linesNew[] = rtrim($start);
            }
            else {
                $linesNew[] = $start . $separator;
            }
            
            $linesNew[] = wordwrap2(trim(substr($line, $maxLength)), $maxLength, $separator);
        }
        else {
            $linesNew[] = $line;
        }
    }
    
    return join("\n", $linesNew);
}

Link to comment
https://forums.phpfreaks.com/topic/181754-solved-wordwrap-text/#findComment-958617
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.