Thread: Picky explode()
View Single Post
Old 06-15-2008, 09:48 PM   #1 (permalink)
Tree
The Wanderer
 
Tree's Avatar
 
Join Date: Jun 2008
Location: Atlanta, USA
Posts: 8
Thanks: 1
Tree is on a distinguished road
Default Picky explode()

I was browsing another forum earlier today and came across someone who wanted to split a string into an array. That's a fairly simple task with explode(). But they also wanted anything in between brackets to be left alone.

I came up with a solution that works fine, but I'm fairly certain there's a better way to do it. Here's what I've got.

PHP Code:
<?php
$string 
"501,Red_Potion,Red Potion,0,50,,70,,,,,0xFFFFFFFF,7,2,,,,,,{ itemheal rand(45,65),0; },{},{}";
echo 
'<pre>';
print_r(picky_explode($string));
echo 
'</pre>'

function 
picky_explode($string) {
    
$array explode(',',$string);
    
$array_size count($array);
    foreach (
$array as $key => $value) {
        
$newvalue '';
        
// The code below combines any array elements between a pair of brackets {}
        
if (strpos($value,'{') !== false) {
            for (
$i $key;$i<=$array_size;$i++) {
                
$newvalue .= ",".$array[$i];
                if (
strpos($array[$i],'}') !== false) {
                    for (
$x=$i;$x>$key;$x--) {
                        
$kill[] = $x;
                    }
                    break;
                }
            }
        } else {
            
$newvalue $value;
        }
        
$array2[] = str_replace(",{""{",$newvalue);
    }
    foreach (
$kill as $value) {
        unset(
$array2[$value]);
    }
    foreach (
$array2 as $value) {
        
$final_array[] = $value;
    }
    return 
$final_array;
}
?>
Any ideas?
__________________
NCIDev.com

Last edited by Tree : 06-15-2008 at 10:43 PM.
Send a message via ICQ to Tree Send a message via AIM to Tree Send a message via MSN to Tree Send a message via Yahoo to Tree
Tree is offline  
Reply With Quote