I would suggest to use "explode" http://php.net/manual/en/function.explode.php for splitting the string by spaces. Then you'll get an array of words on which you can iterate and build your text-parts.
split text into parts
Question
I wanted to split a large text into 10 pieces (somehow equal parts). Ii use this function:
<?php
function chunk($msg) {
$msg = preg_replace('/[\r\n]+/', ' ', $msg);
//define character length of each text piece
$chunks = wordwrap($msg, 10000, '\n');
return explode('\n', $chunks);
}
$arrayys=chunk($t);
foreach($arrayys as $partt){echo $partt."<br/><br/><br/>";}
?>
But is it possible to define word length of each text piece (not character length )? how to divide text into words in such situation?
Solution
OTHER TIPS
From docs,
<?php
$text = "ABCDEFGHIJK.";
$newtext = wordwrap($text,3,"\n",true);
echo "$newtext\n";
?>
OUTPUT: ABC DEF GHI JK.
You can do something like this. Breaks your text into equal parts.. The text in $str
is of 20 chars, So the text is broken into 10 parts with 2 chars as a set.
Say, if your large text is of 1000 characters, then you will be getting 100 equal parts of text.
<?php
$div=10;//Equally split into 10 ...
$str="abcdefghijklmnopqrst";
print_r(array_chunk(str_split($str), (strlen($str)/($div))));
OUTPUT:
Array
(
[0] => Array
(
[0] => a
[1] => b
)
[1] => Array
(
[0] => c
[1] => d
)
[2] => Array
(
[0] => e
[1] => f
)
[3] => Array
(
[0] => g
[1] => h
)
[4] => Array
(
[0] => i
[1] => j
)
[5] => Array
(
[0] => k
[1] => l
)
[6] => Array
(
[0] => m
[1] => n
)
[7] => Array
(
[0] => o
[1] => p
)
[8] => Array
(
[0] => q
[1] => r
)
[9] => Array
(
[0] => s
[1] => t
)
)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow