note 95880 modified in function.preg-split by thiago
| From: | thiago@php.net | Date: | Wed, 27 Jan 2010 03:24:42 +0000 |
| Subject: | note 95880 modified in function.preg-split by thiago | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-165353@lists.php.net to get a copy of this message | ||
Hope this helps 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 = 1)
{
$words = preg_split('/\s/', $string);
$lines = array();
$line = '';
foreach ($words as $k => $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[] = !count($lines) ? trim($line) : $word;
return $lines;
}
?>
--was--
Hope this helps 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 = 1)
{
$words = preg_split('/\s/', $string);
$lines = array();
$line = '';
foreach ($words as $k => $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[] = !count($lines) ? trim($line) : $word;
return $lines;
}
?>
Please disregard previous note.
http://php.net/manual/en/function.preg-split.php