Jump to content

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.