php - string to array, max length, break on words -


i have string break array.

each array needs have set length, let say, 45 characters.

each break point needs based on words , not characters (so, never more 45, in 30'ish range, if long-char word used)

so, let take string

$content = 'sed suscipit enim in consectetur lacus vestibulum efficitur convallis luctus curabitur vehicula massa nec pretium sed maximus nunc in aliquam orci nulla facilisi nullam vulputate ornare dictum sed fermentum sapien nec felis gravida eget consequat ex iaculis vestibulum nec feugiat nisl sed consequat nulla sed in odio congue dictum augue et mollis nunc integer libero leo eleifend sed congue ut ultrices sed nulla integer sapien felis sollicitudin et turpis nec mattis egestas augue phasellus non lectus ac ipsum ultrices consectetur eu @ justo nam'; 

and resulting array (what after)

    $data = [];      $data[] = 'sed suscipit enim in consectetur lacus';     $data[] = 'vestibulum efficitur convallis luctus';     $data[] = 'curabitur vehicula massa nec pretium sed a';     $data[] = 'maximus nunc in aliquam orci nulla facilisi';     $data[] = 'nullam vulputate ornare dictum sed fermentum';     $data[] = 'sapien nec felis gravida eget consequat ex';     $data[] = 'iaculis vestibulum nec feugiat nisl sed';     $data[] = 'consequat nulla sed in odio congue dictum';     $data[] = 'augue et mollis nunc integer libero leo';     $data[] = 'eleifend sed congue ut ultrices sed nulla';     $data[] = 'integer sapien felis sollicitudin et turpis';     $data[] = 'nec mattis egestas augue phasellus non lectus';     $data[] = 'ac ipsum ultrices consectetur eu @ justo nam'; 

each array under 45 characters , based on word length not hard-numbers.

i know can use code break string specific length, based on word , not chars, not sure how make work together.

$content = substr($content, 0, strpos($content, ' ', 45)); 

in case can use wordwrap function , explode or preg_split

first need split string pieces of required length:

$ps = wordwrap($content, 45); 

by default divider \n. can set own:

$ps = wordwrap($content, 45, '===');    // === divider     

next, if need array should explode or preg_split $ps variable. if use custom divider (like ===) can:

$data = explode('===', $ps); 

with \n divider use preg_split:

$data = preg_split('/\n/', $ps); 

so, final code can be:

$data = preg_split('/\n/', wordwrap($content, 45)); 

Comments

Popular posts from this blog

javascript - Slick Slider width recalculation -

jsf - PrimeFaces Datatable - What is f:facet actually doing? -

angular2 services - Angular 2 RC 4 Http post not firing -