Thread: Picky explode()
View Single Post
Old 06-15-2008, 10:38 PM   #2 (permalink)
Wildhoney
La Vida es Sueño
Advanced Programmer Top Contributor 
 
Wildhoney's Avatar
 
Join Date: Sep 2007
Location: Oldham
Posts: 2,280
Thanks: 90
Wildhoney is on a distinguished road
Default

You could probably do this with preg_split, if we were clever enough. However, I for one am not. There are a few on TalkPHP which I'm sure are. This would be my solution:

php Code:
$szString = "501,bleh,{ itemheal rand(45,65),0; },bleh,1,2,3,{ohh,1,2}";
print_r(picky_explode(',', $szString));

function picky_explode($szSplitBy, $szString)
{
    $bInBrackets = false;
    $aReturn = array();
    $aParts = explode($szSplitBy, $szString);
   
    foreach ($aParts as $szPart)
    {
        if (!$bInBrackets)
        {
            $aReturn[] = $szPart;
        }
       
        if (substr($szPart, 0, 1) == '{')
        {
            $bInBrackets = true;
            continue;
        }
       
        $aReturn[count($aReturn) - 1] .= $szSplitBy . $szPart;
       
        if (substr($szPart, -1, 1) == '}')
        {
            $bInBrackets = false;
        }
    }
   
    return $aReturn;
}
__________________
The man who comes back through the Door in the Wall will never be quite the same as the man who went out.
Send a message via AIM to Wildhoney Send a message via MSN to Wildhoney Send a message via Yahoo to Wildhoney
Wildhoney is offline  
Reply With Quote