note 71163 deleted from function.preg-split by danbrown
| From: | danbrown@php.net | Date: | Wed, 27 May 2009 13:49:45 +0000 |
| Subject: | note 71163 deleted from function.preg-split by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-156068@lists.php.net to get a copy of this message | ||
Note Submitter: me
----
[Editor's Note: You can use php's wordwrap() to do the exact same thing]
This script splits a text into portions of a defined max. size, which will never be exceeded, and
doesnt cut words. (Per portion it adds as many words as possible without exceeding the char-limit)
the only exception where a portion would be bigger than the limit, is when there's a word thats
longer than the max_size, but you could quite easily change the script so it regards this.
<?
$str= 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation
ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in
voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.';
$max_size = 50;
$words = preg_split("/[\040]+/", $str, -1);
$r=0;
for($i=0; $i < count($words); $i++) {
if (strlen($line[$r] . $words[$i] . ' ') < $max_size) $line[$r] .= $words[$i] . '
';
else
{
$r++;
$line[$r] .= $words[$i] . ' ';
}
}
print_r ($line);
?>
Result:
Array
(
[0] => Lorem ipsum dolor sit amet, consectetur
[1] => adipisicing elit, sed do eiusmod tempor
[2] => incididunt ut labore et dolore magna aliqua. Ut
[3] => enim ad minim veniam, quis nostrud exercitation
[4] => ullamco laboris nisi ut aliquip ex ea commodo
[5] => consequat. Duis aute irure dolor in
[6] => reprehenderit in voluptate velit esse cillum
[7] => dolore eu fugiat nulla pariatur. Excepteur sint
[8] => occaecat cupidatat non proident, sunt in culpa
[9] => qui officia deserunt mollit anim id est laborum.
)