Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explode array comma but not inside square brackets

Tags:

arrays

loops

php

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?

like image 638
Ian Fraser Avatar asked Mar 22 '26 09:03

Ian Fraser


1 Answers

$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


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!