xanderpower
xanderpower

Reputation: 49

Divide string into words

I'm now having a headache solving this issue.

I have this line :-

$quote = "Success consists of going from failure to failure without loss of enthusiasm.";

How do I break this line such that each broken line would have max 27 characters?

My Desired output would be

array(line 1) --> Success consists of going
array(line 2) --> from failure to failure 
array(line 3) --> without loss of enthusiasm

This is what I've tried :-

$final_lines = array();
      //conver to string array
      $string_arrray_line = str_split($string_line);
      $a = "";
      $b=0;
      $counter = 0;
      for($i=0;$i<strlen($string_line);$i++)
      {
        // echo $i;
        if($counter == 27)
        {
          //insert into array now
          $final_lines[$b] = $a;
          $b++;
          $a = "";
          $counter = 0;
        }
        $a .= $string_arrray_line[$i];
        $counter++;
        // var_dump($string_arrray_line[$i]);
      }

^^ This doesn't work and dozen other solutions that I tried. What could I possibly do to achieve what I want?

Any solution would be helpful.

Upvotes: 1

Views: 69

Answers (1)

Jirka Hrazdil
Jirka Hrazdil

Reputation: 4021

Use wordwrap():

<?php
$quote = "Success consists of going from failure to failure without loss of enthusiasm.";
$result = explode("\n", wordwrap($quote, 27));
var_dump($result);

Upvotes: 5

Related Questions