note 95878 deleted from function.preg-split by thiago
| From: | thiago@php.net | Date: | Wed, 27 Jan 2010 03:24:14 +0000 |
| Subject: | note 95878 deleted from function.preg-split by thiago | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-165352@lists.php.net to get a copy of this message | ||
Note Submitter: nesbert at gmail dot com
----
Hope this is helpful to someone...
<?php
/**
* Split a string into groups of words with a line no longer than $max
* characters.
*
* @param string $string
* @param integer $max
* @return array
**/
function split_words($string, $max = 100)
{
$words = preg_split('/\s/', $string);
$lines = array();
$line = '';
foreach ($words as $word) {
$length = strlen($line . ' ' . $word);
if ($length <= $max) {
$line .= ' ' . $word;
} else if ($length > $max) {
if (!empty($line)) $lines[] = trim($line);
$line = $word;
} else {
$lines[] = trim($line) . ' ' . $word;
$line = '';
}
}
$lines[] = $word;
return $lines;
}
?>