Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a long string without breaking words?

Tags:

I'm looking for something along the line of

str_split_whole_word($longString, $x) 

Where $longString is a collection of sentences, and $x is the character length for each line. It can be fairly long, and I want to basically split it into multiple lines in the form of an array.

For example:

$longString = 'I like apple. You like oranges. We like fruit. I like meat, also.'; $lines = str_split_whole_word($longString, $x); 

Desired output:

$lines = Array(     [0] = 'I like apple. You'     [1] = 'like oranges. We'     [2] = and so on... ) 
like image 666
musicliftsme Avatar asked Jun 29 '12 00:06

musicliftsme


People also ask

How do I split a string into multiple parts?

As the name suggests, a Java String Split() method is used to decompose or split the invoking Java String into parts and return the Array. Each part or item of an Array is delimited by the delimiters(“”, “ ”, \\) or regular expression that we have passed. The return type of Split is an Array of type Strings.

How do you split a string into characters?

Split is used to break a delimited string into substrings. You can use either a character array or a string array to specify zero or more delimiting characters or strings. If no delimiting characters are specified, the string is split at white-space characters.


1 Answers

The easiest solution is to use wordwrap(), and explode() on the new line, like so:

$array = explode( "\n", wordwrap( $str, $x)); 

Where $x is a number of characters to wrap the string on.

like image 138
nickb Avatar answered Oct 09 '22 21:10

nickb