How to parse the below string inside brackets and store name, desc and id in array using php?
NAME1 DESC1
{
10000
}
NAME2 DESC2
{
20000
}
// also remove comments
// c++ file.inc
NAME1 DESC1{1000}NAME2 DESC2{2000}
I tried the below code, but I only get the ID
$inc = file_get_contents($inc_path);
$inc = preg_replace("/[
]/","",$inc);
preg_match_all('/{(.*?)}/', $inc, $matches);
// results
[0]=> string(5) "10000"
[1]=> string(5) "20000"
My expected results are:
[0]=> array(3) {[0] => "NAME1", [1] => "DESC1", [3] => "10000"}
[1]=> array(3) {[0] => "NAME2", [1] => "DESC2", [3] => "20000"}
You could use this regular expression and code, using the m
modifier and ^
anchor:
$re = '/(^\w+)\s+(0x[a-f\d]+)\s+\{\s+(\w+)/m';
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
$res = array_map(function ($match) { return array_slice($match, 1); }, $matches);
See it run on ideone.com