将字符串分为单词

时间:2017-07-08 21:10:55

标签: php regex

我现在很难解决这个问题。

我有这一行: -

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

如何打破此行,使每条折线都最多27个字符?

我想要的输出是

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

这是我尝试过的: -

$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]);
      }

^^这不起作用,并尝试了其他解决方案。 我能做些什么才能实现我的目标?

任何解决方案都会有所帮助。

1 个答案:

答案 0 :(得分:5)

使用wordwrap()

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