gosulove
gosulove

Reputation: 1645

PHP how to convert a complicated Pattern String into 2 Arrays?

I have a String in this format

{value=very big +$5},{value=super big +$10},{value=extra big +$15}

How to convert them into 2 Arrays in such format?

For example:

$name=["very big","super big","extra big"];
$price=["5","10","15"];   // OR  $price=[5,10,15];

I can do that by using explode() if the string format is in a simpler format. However, this format is too complicated. Anyone knows how to do that ?

Upvotes: 0

Views: 50

Answers (3)

Poiz
Poiz

Reputation: 7617

You may try it like the Snippet below suggests. Quick-Test: Here.

<?php

    $string     = '{value=very big +$5},{value=super big +$10},{value=extra big +$15}';
    $arrParts   = explode(',', $string);
    $name       = [];
    $price      = [];
    $result     = [];

    foreach($arrParts as $iKey=>$part){
        $block      = preg_replace(["#^\{.*?=#", "#\}$#"], "", $part);
        $segments   = preg_split("#\s#", $block);   //<== CREATE AN ARRAY WITH 3 COLUMNS

        list($val1, $val2, $val3)   = $segments;
        $namePart                   = $val1 . " {$val2}";
        $pricePart                  = preg_replace("#[\+\-\$]#", "",$val3);
        $name[]                     = $namePart;
        $price[]                    = $pricePart;

        // BONUS: JUST CREATE A 3RD ARRAY WITH NAMED-KEY
        $result[$namePart]          = $pricePart;
    }
    var_dump($name);
    //YIELDS::
    array (size=3)
      0 => string 'very big' (length=8)
      1 => string 'super big' (length=9)
      2 => string 'extra big' (length=9)

    var_dump($price);
    //YIELDS::
    array (size=3)
      0 => string '5' (length=1)
      1 => string '10' (length=2)
      2 => string '15' (length=2)

    var_dump($result);
    //YIELDS::
    array (size=3)
      'very big' => string '5' (length=1)
      'super big' => string '10' (length=2)
      'extra big' => string '15' (length=2)

Upvotes: 1

Dave
Dave

Reputation: 3091

use explode with ',' ,'=' ,'+$'

$string = "{value=very big +$5},{value=super big +$10},{value=extra big +$15}";
$temp_array = (explode(",",$string));
foreach($temp_array as $val)    
{
    $temp_array = (explode("=",$val));  
    $temp_string = $temp_array[1]; 
    $temp_string = str_replace("}","",$temp_string);
    $temp_array = (explode("+$",$temp_string));
    $name[] = $temp_array[0];
    $price[] = $temp_array[1];
}

DEMO

Upvotes: 1

krasipenkov
krasipenkov

Reputation: 2029

You can use regex, for example this should work:

preg_match_all('/value=([\w\s]+)\s\+/', $string, $matches)
preg_match_all('/\$([\d]+)\}/', $string, $matches)

Upvotes: 0

Related Questions