0

I'm trying to split a string after x characters and put it in array. But I need to don't cut word if x is in a middle of a word. What I expect is to split on the word inferior.

I Tried this :

CODE

$string = "Helllooooo I'mmm <strong>theeeeee</strong> <em> woooooorrd</em> theeee loooonnngessttt";
$desired_width = 24;

$str = wordwrap($string, $desired_width, "\n");

var_dump($str);
die;

OUTPUT

string 'Helllooooo I'mmm
<strong>theeeeee</strong>
<em> woooooorrd</em>
theeee loooonnngessttt' (length=86)

How to put it in array ? Is there another method to do that ? a mix between this and explode() ? thanks !

Zagloo
  • 1,297
  • 4
  • 17
  • 34

2 Answers2

1
$string = "Helllooooo I'mmm <strong>theeeeee</strong> <em> woooooorrd</em> theeee loooonnngessttt";
$desired_width = 24;

$str = wordwrap($string, $desired_width, "\n");
$arr = explode("\n", $str);
var_dump($arr);
die;
Bo Chen
  • 436
  • 2
  • 5
  • I did that too (5 minutes ago before) :) thanks ! `$str = explode("\n", wordwrap($string, $desired_width));` – Zagloo Apr 23 '15 at 09:01
1

Try this

$string = "Helllooooo I'mmm <strong>theeeeee</strong> <em> woooooorrd</em> theeee loooonnngessttt";
$desired_width = 24;

$str = wordwrap($string, $desired_width, "***");
$str = explode("***",$str);
var_dump($str);
die;

the output

array(4) {
  [0]=>
  string(16) "Helllooooo I'mmm"
  [1]=>
  string(25) "<strong>theeeeee</strong>"
  [2]=>
  string(20) "<em> woooooorrd</em>"
  [3]=>
  string(22) "theeee loooonnngessttt"
}
Salah
  • 139
  • 6
  • 1
    Huff, good thing OP doesn't have a few asterix in their string! – Rizier123 Apr 23 '15 at 09:03
  • You need to use any text or symbol that is not expected to exist in the string as split point. the problem appears if the string is dynamic and it contains many stars (in this case) or a new line ' /n' (in the previous solution ). – Salah Apr 23 '15 at 09:09