Search code examples
phparraysloops

Explode array comma but not inside square brackets


I have a string:

$var = "[Item 1],[Item 2],[Item, 3]";

When I use explode:

$var = explode(",", $var);

This also explodes out the comma inside the square brackets.

I would like to return:

[Item 1]
[Item 2]
[Item, 3]

Running through a foreach () {} statement which I am using. Any ideas?


Solution

  • $var = "[Item 1],[Item 2],[Item, 3]";
    
    $var = explode("],[", $var);
    
    print_r($var);
    

    --doh forgot that the delimiter is lost so um a crude option to put those [] back in:

    <?php
    $var = "[Item 1],[Item 2],[Item, 3]";
    
    $var = explode("],[", $var);
    
    foreach ($var as $v){
    
      if(substr($v,0,1)!='['){
       $v='['.$v; 
      }
    
        if(substr($v,-1)!=']'){
    $v=$v.']'; 
      }
    
        $out[]=$v; 
    
    
    
    }
    echo '<pre>';
    print_r($out);
    

    may be better to switch to a regular expression split, i'll write that in a sec

    FINIAL sexy answer:

    <?php
    $var = "[Item 1],[Item 2],[Item, 3]";
    
    
    $var = preg_split('/(\B,\B)/', $var);
    
    
    echo '<pre>';
    print_r($var);
    

    demo: http://codepad.viper-7.com/6qgSzB