Search code examples
phpstringpreg-split

Split a string in array elements into an array using explode() or preg_split()


I have an array with each element is a string like this:

$items[0] = "*1*x *2858* in *1* with selected image to print at *http://mysite.com/test.jpg*"

and

$items[1] = "*2*x *2353* in *2* with selected image to print at *http://mysite.com/test1.jpg*"

How can I split this array elements into a 2nd dimension array so that it becomes:

$items[0][quantity] == 1
$items[0][product_id] == 2858
$items[0][variation} == 1
$items[0][selectedImageUrl] == "http://mysite.com/test.jpg"

and

$items[1][quantity] == 2
$items[1][product_id] == 2353
$items[1][variation} == 2
$items[1][selectedImageUrl] == "http://mysite.com/test1.jpg"

Thanks so much for your help!


@Cal

This is what I have when applying your code.

I applied it to my situation and this is what I have:

function parse_my_str($str){
  $bits = explode(' ', $str);
  $out['selectedImageUrl'] = array_pop($bits);
  $out['product_id'] = $bits[1];
  $out['variation'] = $bits[3];
  $bits = explode('*', $str);
  $out['quantity'] = $bits[1];
  return $out;
}

$items = explode("||", $_SESSION['mp_shipping_info']['special_instructions']); 
foreach ($items as $i => $v) {
    $items[$i] = parse_my_str($v);
    print_r($items[$i]);
}

But i've got

Array ( [selectedImageUrl] => *http://youparkrudely.com/files/2012/04/2011-Aston-Martin-Rapide-026.jpg* [product_id] => *2858* [variation] => *1* [quantity] => 1 ) Array ( [selectedImageUrl] => [product_id] => [variation] => [quantity] => )

@Cal

    Array ( 
[selectedImageUrl] => *http://youparkrudely.com/files/2012/04/2011-Aston-Martin-Rapide-026.jpg* 
[product_id] => *2858* 
[variation] => *1* 
[quantity] => 1 ) 
Array ( [selectedImageUrl] => [product_id] => [variation] => [quantity] => )

Solution

  • Updated for new string, using preg_match() instead:

    $str = "*1*x *2858* in *1* with selected image to print at *http://mysite.com/test.jpg*";
    $arr = parse_my_str($str);
    print_r($arr);
    
    function parse_my_str($str){
      preg_match_all('!\\*(.*?)\\*!', $str, $m);
      return array(
        'quantity' => $m[1][0],
        'product_id' => $m[1][1],
        'variation' => $m[1][2],
        'selectedImageUrl' => $m[1][3],
      );
    }
    

    For your example, you'd use the function like this:

    foreach ($items as $k => $v) $items[$k] = parse_my_str($v);