Dbrandt
Dbrandt

Reputation: 659

How to grab value of custom tag and value between tag

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.

Upvotes: 5

Views: 111

Answers (4)

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167182

Working Code, slightly modified version of walkerneo:

Others can build upon my code or suggest me in doing something better:

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

Fiddle: http://phpfiddle.org/main/code/n1i-e1p

Upvotes: 1

Somy A
Somy A

Reputation: 1712

If allowed to use multiple preg_match, this may be a solution:

    $str = '[cpu]4[cpu] cores and [ram]16gb[ram][hdd]1TB[hdd]asdaddtgg[vga]2gb[vga]';
    $arrResult = array();
    preg_match_all('/(\[[A-Za-z0-9]+\][A-Za-z0-9]+\[[A-Za-z0-9]+\])/i', $str, $match,PREG_SET_ORDER);
    if (is_array($match)) {
        foreach ($match as $tmp) {
            if (preg_match('/\[([A-Za-z0-9]+)\]([A-Za-z0-9]+)\[([A-Za-z0-9]+)\]/', $tmp[0], $matchkey)) {
                $arrResult[$matchkey[1]] = $matchkey[2];
            }
        }
    }

    var_dump($arrResult);

Result:

array(4) {
  'cpu' =>
  string(1) "4"
  'ram' =>
  string(4) "16gb"
  'hdd' =>
  string(3) "1TB"
  'vga' =>
  string(3) "2gb"
}

Upvotes: 0

mowwwalker
mowwwalker

Reputation: 17364

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.

Upvotes: 4

kittycat
kittycat

Reputation: 15045

$string = '[cpu]4[cpu] cores and [ram]16gb[ram]';

preg_match('|\[([^\]]+)\]([^\[]+)\[/?[^\]]+\][^\[]+\[([^\]]+)\]([^\[]+)\[/?[^\]]+\]|', $string, $matches);
$array = array($matches[1] => $matches[2], $matches[3] => $matches[4]);

print_r($array);

Upvotes: 1

Related Questions