Reputation: 659
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
Reputation: 167182
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>
Upvotes: 1
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
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:
[
or ]
can appear in []
as the tag.[
or ]
can be the value of the tagUpvotes: 4
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