将csgo_items.txt转换为数组以显示在表中

时间:2014-11-20 11:48:54

标签: php arrays regex

我想在PHP中解析以下文本并将其显示在表中,因为我需要经常查找ID,而且我不喜欢经常搜索文件。 看起来像这样

"1"
{
    "name"      "weapon_deagle"
    "prefab"        "weapon_deagle_prefab"
    "item_quality"      "normal"
    "baseitem"      "1"
    "default_slot_item"     "1"
    "item_sub_position"     "secondary4"
}
"2"
{
    "name"      "weapon_elite"
    "prefab"        "weapon_elite_prefab"
    "item_quality"      "normal"
    "baseitem"      "1"
    "default_slot_item"     "1"
    "item_sub_position"     "secondary1"
}

我尝试使用explode和“}”作为分隔符来解析这些,但它总是给我带来奇怪的结果。 我听说过用RegEx这样做,但我不确定。

我的尝试:

$items = file_get_contents('items.txt');
$arr = explode("}", $items);

文本可能已经是我可以解析的格式吗?或者这是一个自定义的?

1 个答案:

答案 0 :(得分:0)

"(\d+)"(?=(?:[^{}]*{[^{}]*})*[^{}]*$)|"([^"]+)"\s+"([^"]+)"

试试这个。抓住捕获。参见演示。

http://regex101.com/r/lZ5mN8/65

$re = "/\"(\\d+)\"(?=(?:[^{}]*{[^{}]*})*[^{}]*$)|\"([^\"]+)\"\\s+\"([^\"]+)\"/s";
$str = "\"1\"\n{\n \"name\" \"weapon_deagle\"\n \"prefab\" \"weapon_deagle_prefab\"\n \"item_quality\" \"normal\"\n \"baseitem\" \"1\"\n \"default_slot_item\" \"1\"\n \"item_sub_position\" \"secondary4\"\n}\n\"2\"\n{\n \"name\" \"weapon_elite\"\n \"prefab\" \"weapon_elite_prefab\"\n \"item_quality\" \"normal\"\n \"baseitem\" \"1\"\n \"default_slot_item\" \"1\"\n \"item_sub_position\" \"secondary1\"\n}";

preg_match_all($re, $str, $matches);