note 53033 modified in function.str-split by aidan

From: Date: Sat, 04 Feb 2006 07:15:20 +0000
Subject: note 53033 modified in function.str-split by aidan
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-102971@lists.php.net to get a copy of this message
[Editor's Note: Or just: php.net/wordwrap] This is a little function to split a string into shorter strings with max lenght $n in such way, that it don't split words (it search for spaces), it's usefull for articles or sth. Result is put in $ttab variable, and function result is number of "pages". <?php function divide_text($text, $n, &$ttab) { $ttab = array(); $l = strlen($text); // text length $cb = 0; //copy begin from.. $p = 0; // parts if ($l <= $n) { $ttab[0] = $text; return 1; } else { $ctrl = 1; while(((($p-1) * $n) < $l) && ($ctrl < 100)) { $crtl++; // control variable, to protect from infinite loops $tmp = substr($text, $cb, $n); // we're looking for last space in substring $lastpos = strrpos($tmp," "); if ( (is_bool($lastbool) && !$lastpos) || ( $l - $cb <= $n)) { $ttab[$p] = $tmp; } else { $tmpgood = trim(substr($tmp, 0,$lastpos)); // if they were another spaces at the end.. $ttab[$p] = $tmpgood; $cb += $lastpos + 1 ; }; // if $p++; }; //for return $p; }; // if } // divide text ?> --was-- This is a little function to split a string into shorter strings with max lenght $n in such way, that it don't split words (it search for spaces), it's usefull for articles or sth. Result is put in $ttab variable, and function result is number of "pages". <?php function divide_text($text, $n, &$ttab) { $ttab = array(); $l = strlen($text); // text length $cb = 0; //copy begin from.. $p = 0; // parts if ($l <= $n) { $ttab[0] = $text; return 1; } else { $ctrl = 1; while(((($p-1) * $n) < $l) && ($ctrl < 100)) { $crtl++; // control variable, to protect from infinite loops $tmp = substr($text, $cb, $n); // we're looking for last space in substring $lastpos = strrpos($tmp," "); if ( (is_bool($lastbool) && !$lastpos) || ( $l - $cb <= $n)) { $ttab[$p] = $tmp; } else { $tmpgood = trim(substr($tmp, 0,$lastpos)); // if they were another spaces at the end.. $ttab[$p] = $tmpgood; $cb += $lastpos + 1 ; }; // if $p++; }; //for return $p; }; // if } // divide text ?> http://php.net/manual/en/function.str-split.php

« previous php.notes (#102971) next »