note 108090 added to function.preg-split

From: Date: Tue, 27 Mar 2012 23:11:38 +0000
Subject: note 108090 added to function.preg-split
Groups: php.notes 
Request: Send a blank email to php-notes+get-186881@lists.php.net to get a copy of this message
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 } ?> ---- Server IP: 212.124.37.9 Probable Submitter: 78.43.35.118 ---- Manual Page -- http://www.php.net/manual/en/function.preg-split.php Edit -- https://master.php.net/note/edit/108090 Del: integrated -- https://master.php.net/note/delete/108090/integrated Del: useless -- https://master.php.net/note/delete/108090/useless Del: bad code -- https://master.php.net/note/delete/108090/bad+code Del: spam -- https://master.php.net/note/delete/108090/spam Del: non-english -- https://master.php.net/note/delete/108090/non-english Del: in docs -- https://master.php.net/note/delete/108090/in+docs Del: other reasons-- https://master.php.net/note/delete/108090 Reject -- https://master.php.net/note/reject/108090 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#186881) next »