PHP string analysis
I am trying to parse a string in PHP:
-father_name "John" -father_weight 44.50
-kid >name "Marko" >age 12
-kid >name "Sevda" >age 17
-kid >name "Nathan" >age 19
There are two main forms of FORMS:
- Attributes (e.g. -father, -weight, -kid)
- Sub-attributes (e.g.> name, age)
Note: Attributes are NOT FIXED and DO NOT ALWAYS MOVE in single space.
And their VALUES are of two types:
- String (for example, "Marco")
- Int or decimal (e.g. 12.00)
OUTPUT:
$array['attributes'] = array('father_name ','father_weight ');
$array['attributes']['kid'][] = array('name' => "Marko", 'age' => 12);
$array['attributes']['kid'][] = array('name' => "Sevda", 'age' => 17);
$array['attributes']['kid'][] = array('name' => "Nathan", 'age' => 19);
It must return FORMS (attrs and sub-attrs) and VALUES SEPARATELY.
How can I parse this string in PHP ?
Last note: The solution I found for this is: YAML.
Try the following:
function parse_attributes($string, $separators = array('-','>'), $level = 0){
$attributes = explode($separators[$level], $string);
$attrs = array();
$ret_arr = array();
foreach($attributes as $attribute){
if(!empty($attribute)){
$ex_attr = explode(' ',$attribute);
if(!empty($ex_attr[1])){
if(count($separators) > $level && strpos($attribute, $separators[$level+1])){
$ret = parse_attributes($attribute, $separators, $level+1);
array_push($ret_arr, $ret);
}
if (empty($ret_arr))
$attrs[$ex_attr[0]] = str_replace('"', '', $ex_attr[1]);
else
$attrs[$ex_attr[0]] = $ret_arr;
}
}
}
return $attrs;
}
Using:
$returned = parse_attributes('-father_name "John" -father_weight 44.50 -kid >name "Marko" >age 12 -kid >name "Sevda" >age 17 -kid >name "Nathan" >age 19');
print_r($returned);
:
Array
(
[father_name] => John
[father_weight] => 44.50
[kid] => Array
(
[0] => Array
(
[name] => Marko
[age] => 12
)
[1] => Array
(
[name] => Sevda
[age] => 17
)
[2] => Array
(
[name] => Nathan
[age] => 19
)
)
)
:
echo($returned['kid'][0]['name']);
:
. , , .
, .
$output = array();
$input = explode('-', $input);
foreach ($input as $attribute) {
$attribute = explode('>', $attribute);
if (count($attribute) == 1) {
$attribute = explode(' ', trim($sub_attribute), 2);
$output[$attribute[0]] = eval($attribute[1]);
} else {
$attribute_name = trim($attribute[0]);
if (!isset($output[$attribute_name]) {
$output[$attribute_name] = array();
}
$sub_attribute_output = array();
for ($i = 1; $i < count($attribute); $i++) {
$sub_attribute = explode(' ', trim($attribute[$i]), 2);
$sub_attribute_output[$sub_attribute[0]] = eval($sub_attribute[1]);
}
$output[$attribute_name][] = $sub_attribute_output;
}
}