How to grab value of custom tag and value between tag

arrays, php, regex

Solution

My PHP is rusty, but maybe:

$str = "Server has [cpu]4[cpu] cores and [ram]16gb[ram] and [memory]2tb[/memory]";
$matches = array();
preg_match_all('/\[(\w+)\]([^\[\]]+)\[\/?\w+\]/', $str, $matches);
$output = array_combine($matches[1], $matches[2]);

Details:

- Anything but a `[` or `]` can appear in `[]` as the tag.

- Anything but a `[` or `]` can be the value of the tag

- The closing tag doesn't need to match the starting tag. You could use a backreference, but then it would be case sensitive.

Problem

The idea is to grab values from the following string. ``` String: Server has [cpu]4[cpu] cores and [ram]16gb[ram] ``` I need to grab the tags value and what is between the tag dynamically: should not matter what is between `[*]*[*]` Output: Should be an array as follows ``` Array( 'cpu' => 4, 'ram' => '16gb' ) ``` Having a lot of trouble with the regex pattern. Any help would be appreciated. EDIT: the value between tags or the tags themselves can be anything - Alphanumeric or Numeric. The sample string is a sample only. Tags can appear unlimited times and the array therefore needs to be populated on the fly - not manually.

Original source