note 19548 deleted from function.substr by aidan

From: Date: Sat, 03 Jul 2004 07:56:11 +0000
Subject: note 19548 deleted from function.substr by aidan
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-72391@lists.php.net to get a copy of this message
Note Submitter: jorgenj@stud.ntnu.no ---- 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.

« previous php.notes (#72391) next »