0

I have this variable in php:

$log = "
- [ADD] Lorem Ipsum.
- [FIX] consetetur sadipscing elitr.
- [IMP] sed diam voluptua.";

I'm trying to create the following 2-D array like:

$logarray = array (
        array (
            "type" => "ADD",
            "description" => "Lorem Ipsum."
        ),
        array (
            "type" => "FIX",
            "description" => "consetetur sadipscing elitr."
        ),
        array (
            "type" => "IMP",
            "description" => "sed diam voluptua."
        )
);

I am thinking of using the function explode() but I do not know how in this case. Any help is appreciated.

3
  • regular expressions would be more convenient in this case Commented Aug 28, 2017 at 1:15
  • You're right, the expression has to be able to recognize the text inside the [] for the type Commented Aug 28, 2017 at 1:17
  • And the description as well \[[^\]]+\]\s+[^\n]+ Commented Aug 28, 2017 at 1:20

1 Answer 1

1

We can do this by either using reg exp or completely using string functions by PHP. Here is the code using reg exp:

$log = "
  [ADD] Lorem Ipsum.
- [FIX] consetetur sadipscing elitr.
- [IMP] sed diam voluptua.";
$log_parts = explode('-', trim($log));
$b = array_map("type_element", $log_parts);
print_r($b);

function type_element($log_part)
{
    preg_match("/\[[^\]]*\]/", $log_part, $element_type);
    return array( 
       'type' => $element_type[0], 
       'description' => preg_replace("/\[[^\]]*\]/", "", $log_part)
    );
}

In above code, at first, we made it an array by a fixed pattern '-'. Please notice that, the first line of string has no '-', its better to remove to make it usable for explode().

And then used a method to get the desired array from each string.

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.