note 108090 deleted from function.preg-split by danbrown
| From: | danbrown@php.net | Date: | Thu, 10 May 2012 17:52:27 +0000 |
| Subject: | note 108090 deleted from function.preg-split by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-187683@lists.php.net to get a copy of this message | ||
Note Submitter: Daniel Petrovic
----
Someone wrote the function to split string into words with max length.
Here comes more optimized version:
<?php
/**
6 * Split string into group of lines containing only words,
7 * having maximum line length $max characters
8 *
9 * @param string $longtext
10 * @param integer $max,
11 * @return array - lines of words with $max line length
12 */
13
14 function split_words($longtext, $max = 1)
15 {
16 // spaces or commas are not considered to be words
17 // between '[' and ']' can be put all characters considered to be
18 // word separators
19 $words = preg_split('/[\s,]+/', $longtext, null, PREG_SPLIT_NO_EMPTY);
20 $add_line = false;
21 $current_line = '';
22 $lines = array();
23
24 do {
25 $word = next($words);
26 $wlen = strlen($word);
27 if ($wlen > $max) continue;
28 $current_line = ltrim($current_line);
29 $llen = strlen($current_line);
30 if (!$wlen && $llen) {
31 $lines[] = ltrim($current_line);
32 break;
33 }
34 $add_line = ( $llen + $wlen + 1 > $max);
35 if ($add_line && $llen) {
36 $lines[] = $current_line;
37 $current_line = $word;
38 } else {
39 $current_line .= ' ' . $word;
40 }
41 } while ($word);
42
43 return $lines;
44 }
?>