note 19548 added to function.substr

From: Date: Sat, 02 Mar 2002 23:42:46 +0000
Subject: note 19548 added to function.substr
Groups: php.notes 
Request: Send a blank email to php-notes+get-27286@lists.php.net to get a copy of this message
I wanted to split a string with certain intervals, but not in the middle of a word. This was the method I came up with: <?php // Starts at $i and goes back until it encounters a space: function findSpace($string,$i){ while($i>0) { if($string{$i} == " ")break; else $i--; }; return $i; }; // Then this code splits $yourstring: $start = 0; $n = 0; while(void){ $diff = strlen($yourstring)-$start; if($diff<40){ $part[$n] = substr($yourstring,$start,$diff); break; }; $stop = findSpace($yourstring,$start+40); $length = $stop-$start; $part[$n] = substr($yourstring,$start,$length); $start = $stop; $n++; }; ?> Now the different parts of the string is stored in the array $part. The number 40 is the maximum of characters in each part. You can also put the code for splitting in a function if you need to split many strings, but then $part needs to be assigned first outside the function, and then again as global inside the function. -- http://www.php.net/manual/en/function.substr.php http://master.php.net/manage/user-notes.php?action=edit+19548 http://master.php.net/manage/user-notes.php?action=delete+19548 http://master.php.net/manage/user-notes.php?action=reject+19548

« previous php.notes (#27286) next »