2

Imagine I have 150 characters long string. I would like to divide it into 3 parts, each max 50 characters long. The trick is I also have to keep words intact while dividing the string into 3 parts.

I could use substr and check if it cut the word into half or not. I would like to know if there is any other elegant way to do this.

I also have to keep it in mind that the string might have less than 150 characters. For example if it is 140 characters long then it should be 50 + 50 + 40.

In case if it is less than 100 than it should be 50 + 50. If it is 50 characters or less it shouldn't divide the string.

I would be glad to hear your ideas / ways to approach this.

Thank you in advance for your time and concern.

sree
  • 498
  • 4
  • 19
Revenant
  • 2,942
  • 7
  • 30
  • 52
  • possible duplicate of [How to Truncate a string in PHP to the word closest to a certain number of characters?](http://stackoverflow.com/questions/79960/how-to-truncate-a-string-in-php-to-the-word-closest-to-a-certain-number-of-chara) – codaddict May 04 '12 at 12:08
  • 2
    ref: [wordwrap](http://php.net/manual/function.wordwrap.php) – Yoshi May 04 '12 at 12:09

2 Answers2

5

Sounds like you just want the php function wordwrap()

 string wordwrap ( string $str [, int $width = 75 [, string $break = "\n" [, bool $cut = false ]]] )

Wraps a string to a given number of characters using a string break character.

AD7six
  • 63,116
  • 12
  • 91
  • 123
1

I dont think this is the best solution performance-wise but it's somehting

$text = 'Lorem te...';
$strings = array(0=>'');
$string_size = 50;
$ci = 0;
$current_len = 0;
foreach( explode(' ', $text) as $word ) {
  $word_len = strlen($word) + 1;
  if( ($current_len + $word_len) > ($string_size - 1) )
    $strings[$ci] = rtrim( $strings[$ci] );
    $ci++;
    $current_len = 0;
    $strings[$ci] = '';
  }

  $strings[$ci] .= $word.' '; 
  $current_len = $current_len + $word_len;
}
xCander
  • 1,338
  • 8
  • 16