2

I have specific string to parse, and create php array key value pair out of it. Was not clever about this, cannot find suitable solution at this point. The string looks like this:

{xxx} some text 1{*|, some text 2 {xxx}}{*|, some text 3 {xxx}}{*|, 1 {xxx} some text 4}{*|, 1 {xxx} some text 5}

And I need to create php array like this:

[
    '{xxx} some text 1' => 'some text 2 {xxx}'
    '{xxx} some text 1' => 'some text 3 {xxx}'
    '{xxx} some text 1' => '1 {xxx} some text 4'
    '{xxx} some text 1' => '1 {xxx} some text 5'
]

What have I tried:

  1. First replace {xxx} this curly braces with something else, so I am left with less of them

        $value = str_replace('@#', '{', $value);
        $value = str_replace('#@', '}', $value);
    
  2. Now I tried somehow to explode based on }{ rule, but somehow I it did not work for me.

I tried a bunch of stuff, but code is messy to paste it here, but if someone experienced can point me to the right path I would be very grateful. Maybe there is better approach for this issue which I cannot see with the lack of experience.

2
  • 1
    Why not split on the string {*|, ? Also, I think your example is wrong-- you repeat some text 1 in your "output" array. Commented Jun 6, 2019 at 17:30
  • I see, you are right, I guess it should be reversed, not to have same keys. Commented Jun 6, 2019 at 17:34

1 Answer 1

1

You could create an array of those values by the {*|, pattern using explode function and then build up a new array with each of the values matching the first value as a key.

Please note that you can't have the same key in an associative array so you either have to make a sub array with same key => value pair like so :

$str = '{xxx} some text 1{*|, some text 2 {xxx}}{*|, some text 3 {xxx}}{*|, 1 {xxx} some text 4}{*|, 1 {xxx} some text 5}';

$values = explode('{*|,', $str);

$newArray = [];
for ($i = 1; $i < count($values); $i++) {
    $newArray[$i][$values[0]] = $values[$i];     
}

var_dump($newArray);

Output here : https://3v4l.org/ZS461

Or create an array named with the first key name with the values inside of it like this :

$str = '{xxx} some text 1{*|, some text 2 {xxx}}{*|, some text 3 {xxx}}{*|, 1 {xxx} some text 4}{*|, 1 {xxx} some text 5}';

$values = explode('{*|,', $str);

$newArray = [];
for ($i = 1; $i < count($values); $i++) {
    $newArray[$values[0]][$i - 1] = $values[$i];    
}

var_dump($newArray);

Output here : https://3v4l.org/9JgGg

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.