我想从txt文件中获取一些信息。。。我已经通读了一些问题,但我的一个没有解决方案
inventoryItemData {
header {
id: 3758164995
}
itemType: 1
itemID: 2561
count: 1
isOwnerList: false
fromLand: 0
sourceLen: 0
}
这在我的文本文件中,我想获得项目类型和项目ID作为字符串,因此在本例中类似
'(2561,1)'
我知道我可以使用foreach并将每个字符串保存到一个数组中,但我不知道如何获得两个数字
$file = fopen('input.txt', "r");
$itemID = '';
$itemType = '';
while($line = fgets($file))
{
if(preg_match('/itemType: ('d+)/', $line, $matches))
{
$itemType = $matches[1];
}
else if(preg_match('/itemID: ('d+)/', $line, $matches))
{
$itemID = $matches[1];
}
}
$string = "($itemID,$itemType)";
print $string . "'n";
编辑以及能够支持文件中多个条目的版本
$file = fopen('input.txt', "r");
$itemID = null;
$itemType = null;
$arrayAssoc = array();
$arrayStrings = array();
while($line = fgets($file))
{
if(preg_match('/itemType: ('d+)/', $line, $matches))
{
$itemType = $matches[1];
}
else if(preg_match('/itemID: ('d+)/', $line, $matches))
{
$itemID = $matches[1];
}
if($itemType != null && $itemID != null)
{
$arrayAssoc[$itemID] = $itemType;
$arrayString[] = "($itemID,$itemType)";
$itemType = $itemID = null;
}
}
print_r($arrayAssoc);
print_r($arrayString);
这应该适用于您:
(首先,我将所有行放入一个具有file()
的数组中。然后,我获取具有preg_grep()
的所有行,这些行是(包含)$search
数组的一个元素。最后,我只是用preg_filter()
out)过滤搜索中的文本
<?php
$lines = file("test.txt", FILE_IGNORE_NEW_LINES);
$search = ["itemType:", "itemID:"];
$arr = preg_filter("/('b" . implode("|'b", $search) . ")/", "", preg_grep("/('b" . implode("|'b", $search) . ")/", $lines));
print_r($arr);
?>
输出:
Array ( [4] => 1 [5] => 2561 )