如何使用php解析括号内的下面的字符串并在数组中存储名称,desc和id?
NAME1 DESC1
{
10000
}
NAME2 DESC2
{
20000
}
// also remove comments
// c++ file.inc
NAME1 DESC1{1000}NAME2 DESC2{2000}
我尝试了以下代码,但我只获得了ID
$inc = file_get_contents($inc_path);
$inc = preg_replace("/[\n\r]/","",$inc);
preg_match_all('/{(.*?)}/', $inc, $matches);
// results
[0]=> string(5) "10000"
[1]=> string(5) "20000"
我的预期结果是:
[0]=> array(3) {[0] => "NAME1", [1] => "DESC1", [3] => "10000"}
[1]=> array(3) {[0] => "NAME2", [1] => "DESC2", [3] => "20000"}
答案 0 :(得分:0)
您可以使用m
修饰符和^
锚点来使用此正则表达式和代码:
$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);
上查看它