Re: whats wrong in this program.

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



I think I finally understand what you are trying to do. I don't see any reason why you need to use the token functions, and I would recommend using array functions instead (also, it is exceedingly easy to sort the elements of an array... see the end).

I believe this will do what you are trying to do:
//Tokenizer for Babu
$str = '10,12,14-18';
$commas = explode(',', $str); // $commas will be an array of three items in this case

// Final Values will go into the $final array
$final = array();
foreach ($commas as $value) {
// If one of the $commas elements contains a dash, we need to get the range between them!
    if (strstr($value, '-')) {
// Explode based on the dash. This code assumes there will only be a single dash
        $rangeValues = explode('-', $value);
        foreach (range($rangeValues[0], $rangeValues[1]) as $number) {
            $final[] = $number;
        }
    } else {
// If $value does not contain a dash, add it directly to the $final array
        $final[] = $value;
    }
}
echo "All your values in the range $str are ".implode(' ', $final);
// Prints "All your values in the range 10,12,14-18 are 10 12 14 15 16 17 18"


In your last email, you had some of the values given out of order:
1.  20,21-24
2. 21-24,20
3. 10,20,21-24,25,26,30

To make sure the $final values are always ascending, just do this at the end:
sort($final);

Done!!

Jordan




On Sep 13, 2005, at 7:16 PM, babu wrote:

$str=10,12,14-18;

$tok = strtok($str, ',');
while ($tok !== false) {
 $toks[] = $tok;
  $tok = strtok(',');
   }

foreach ($toks as $token){
 if (strpos($token,'-')){
  stringtokenize($token);
 }else{
  $finaltokens[]= $token;
  }
}

function stringtokenize($nstr){
 $ntok1= strtok($nstr,'-');
 $ntok2=strtok('-');
 for($i=$ntok1;$i<=$ntok2;$i++){
  $finaltokens[]= $i;
  }
 }

foreach ($finaltokens as $ftoken){
 echo $ftoken;
 echo "<br />";
 }

the ouput prints only 10,12 but not 14,15,16,17,18. where is the problem.



---------------------------------
To help you stay safe and secure online, we've developed the all new Yahoo! Security Centre.

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux