gpt4 book ai didi

php - 如何将此字符串拆分为数组?

转载 作者:行者123 更新时间:2023-12-04 16:17:50 24 4
gpt4 key购买 nike

所以我有一些查询游戏服务器的数据,我需要找到一种方法来提取这些信息,以便它可以在我的网站上使用。

# 7 "player1" 1156 STEAM_0:4:00100365   0 09:52   84    3 175.77.234.241:27505
# 8 "player2" 1149 STEAM_0:0:39163243 2 14:05 52 0 109.175.131.239:65423
# 9 "player " 1159 STEAM_0:0:162 31 07:19 45 0 78.1.126.130:27025
#10 "gameer123" 1146 STEAM_0:0:701135 4 16:41 94 0 191.200.0.100:14097

上面几行的格式是:"id""name""userid""uniqueid""frag""time""ping""loss""adr"

我如何提取这些信息并将其转换成一个数组,这样我就有了这样的东西

[0] => Array
(
[Id] => 0
[Name] => Player0
[Frags] => 0
[Time] => 50856
[Uniqueid] => STEAM_0:4:001534362
)

[1] => Array
(
[Id] => 0
[Name] => Player1
[Frags] => 4
[Time] => 1447
[Uniqueid] => STEAM_0:4:00100365
)

顺便说一句,我只需要玩家姓名、片段、时间和唯一 ID。

最佳答案

这是另一种 RegEx 方法,使用命名模式,这些模式直接回收到干净的最终数组的数组键中。您可以将此处建议的任何 RegEx 模式集与以下解决方案一起使用,只需添加 (?<Keyname>...)在每个模式的括号的开头进行命名。

$data = <<<EOL
# 7 "player1" 1156 STEAM_0:4:00100365 0 09:52 84 3 175.77.234.241:27505
# 8 "player2" 1149 STEAM_0:0:39163243 2 14:05 52 0 109.175.131.239:65423
# 9 "player" 1159 STEAM_0:0:162 31 07:19 45 0 78.1.126.130:27025
#10 "gameer123" 1146 STEAM_0:0:701135 4 16:41 94 0 191.200.0.100:14097
EOL;

/* Matching the source data with named patterns */

preg_match_all('#(?<Id>\d+)\s+"(?<Name>[[:alnum:]]+)"\s+\d+\s+(?<Uniqueid>STEAM_[0-9_:]+)\s+(?<Frags>\d+)\s+(?<Time>[\d:]{5})#m', $data, $fields, PREG_SET_ORDER);

/* Cleaning up the numeric keys from RegEx matches */

foreach($fields as $num=>$set) {
$fields[$num] = array_diff_key($set, array_flip( array_filter( array_keys($set), 'is_int')) );
}

print_r($fields);

结果:

Array
(
[0] => Array
(
[Id] => 7
[Name] => player1
[Uniqueid] => STEAM_0:4:00100365
[Frags] => 0
[Time] => 09:52
)

[1] => Array
(
[Id] => 8
[Name] => player2
[Uniqueid] => STEAM_0:0:39163243
[Frags] => 2
[Time] => 14:05
)

[2] => Array
(
[Id] => 9
[Name] => player
[Uniqueid] => STEAM_0:0:162
[Frags] => 31
[Time] => 07:19
)

[3] => Array
(
[Id] => 10
[Name] => gameer123
[Uniqueid] => STEAM_0:0:701135
[Frags] => 4
[Time] => 16:41
)

)

请注意,我已经从 "player " 中删除了源数据的第三行进入"player" ,假设这是一个错字。如果玩家名称有其他字符,请将它们添加到:(?<Name>[[:alnum:] _-]+)等等

========

我将命名模式 int-key-cleaner 回收到一个函数中,以防有人需要经常使用。

    /* In place of the foreach-loop above, use: */

$fields = remove_int_keys_pma($fields);

/* And stick these two functions somewhere. */

/* Remove integer keys from preg_match_all sets. (Must use PREG_SET_ORDER.) */

function remove_int_keys_pma($array) {
foreach($array as $k=>$set) {
$array[$k] = remove_int_keys($set);
}
return $array;
}

/* Remove integer keys from an array. */

function remove_int_keys($array) {
return array_diff_key($array, array_flip( array_filter( array_keys($array), 'is_int')) );
}

关于php - 如何将此字符串拆分为数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31091639/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com