user2450639
user2450639

Reputation: 306

Create php array based on specific rule

I need to create php array from the string, and then after parse the array.

So, the rules are like this:

{Test1|Test2} {Test3|Test4}

Parse this string and make it to be php array like this:

[
    'Test1' => Test2,
    'Test3' => Test4,
]

and this is something that I succeded with preg_match:

preg_match('/\{(.+)?\|(.+)}/', $attributeValue, $matches);

but there is another condition that I could not solve with preg_match and that is:

 {1|1 Test ({5622} text)}

where result would be

[
    '1' => 1 Test ({5622} text),
]

Basically , I cannot solve this when curly brackets are inside of the condition, I always get some unexpected result. Please, help me go in the right direction, I don't know if the preg_match is the best solution for my case.

Upvotes: 1

Views: 47

Answers (2)

Pupil
Pupil

Reputation: 23958

You have to explode() the string first.

Steps:

1) explode() string with } {.

2) Now, loop over resulting array.

3) In the loop, replace any { and }

4) Again, in the loop explode() by |.

5) You will get two string (array elements).

6) First element is your desired key and second is the desired value.

7) Append the key value pair to a new blank array.

8) Enjoy!!!

Working Code:

<?php
$string = '{Test1|Test2} {Test3|Test4}';
$finalArray = array();
$asArr = explode( '} {', $string );
$find = ['{', '}'];
$replace = ['', ''];
foreach( $asArr as $val ){
 $val = str_replace($find, $replace, $val);
  $tmp = explode( '|', $val );
  $finalArray[ $tmp[0] ] = $tmp[1];
}
echo '<pre>';
print_r($finalArray);
echo '</pre>';

Output:

Array
(
    [Test1] => Test2
    [Test3] => Test4
)

Another version of the same code with less lines of code:

$string = "{Test1|Test2} {Test3|Test4}";
$string = str_replace('{', '', $string);
$arr = array_filter(explode('}', $string));
foreach($arr as $item){
 $item = explode('|', $item);
 $result[trim($item[0])] = trim($item[1]);
}
echo '<pre>';print_r($result);echo '</pre>';

Upvotes: 1

Dhaval Panara
Dhaval Panara

Reputation: 86

You can use below code get your desire output. There is no need to use preg_match.

$string = "{Test1|Test2} {Test3|Test4}";

$string_array = array_filter(explode('}', $string));
$result = [];
foreach($stringarray as $item){
  $item = str_replace('{', '', $item);
  $item_array = explode('|', $item);
  $result[$item_array[0]] = $item_array[1];
}
echo "<pre>";
print_r($result);

Output:

Array
(
    [Test1] => Test2
    [ Test3] => Test4
)

Upvotes: 1

Related Questions