我有一个看起来像这样的文件(带有换行符和奇怪的间距):
Player: Alive: Score: Ping: Member of Team:
player1 No 16 69 dogs
bug Yes 2 63 insects
name with space No 0 69 cats
bob No 0 69 dogs
如何抓住第一列并将其转换为数组?
期望输出:
$ players [1] ----> “player1”
$ players [2] ----> “错误”
$ players [3] ----> “空间名称”
$ players [4] ----> “鲍勃”
答案 0 :(得分:6)
<?php
$a=file('file.txt');
$pos=strpos($a[0],'Alive:');
$res=array_map(function($x) use ($pos){
return trim(substr($x,0,$pos));
},$a);
unset($res[0]);
对于PHP 5.2 -
<?php
$a=file('file.txt');
$pos=strpos($a[0],'Alive:');
function funcname($x,$pos){
return trim(substr($x,0,$pos));
}
$res=array_map('funcname',$a,array_fill(0,count($a),$pos));
unset($res[0]);
答案 1 :(得分:3)
使用正则表达式的另一个选项可能如下:
preg_match_all('/^.{0,15}?(?= {2}|(?<=^.{15}))/m', $subject, $matches);
$players = $matches[0];
unset($players[0]); // remove header
var_export($players);
生成的$players
数组看起来像
array (
1 => 'player1',
2 => 'bug',
3 => 'name with space',
4 => 'bob',
)
注意:与任何基于正则表达式的解决方案一样,如果上面看起来像魔术,那么请不要使用它。如果您不知道它实际上要匹配的内容,那么将正则表达式复制并粘贴到代码中绝对没有意义。
答案 2 :(得分:1)
这是迭代器的一种方法:
class SubstringIterator extends IteratorIterator
{
protected $startAtOffset, $endAtOffset;
public function __construct($iterator, $startAtOffset, $endAtOffset = null) {
parent::__construct($iterator);
$this->startAtOffset = $startAtOffset;
$this->endAtOffset = $endAtOffset;
}
public function current() {
return substr(parent::current(), $this->startAtOffset, $this->endAtOffset);
}
}
您可以这样使用它:
$playerIterator = new LimitIterator(
new SubstringIterator(
new SplFileObject('yourFile.txt'),
0, // start at beginning of line
15 // end before Alive:
)
, 1 // start at line 2 in file (omits the headline)
);
然后你可以通过迭代器foreach
,例如
foreach ($playerIterator as $player) {
echo $player, PHP_EOL;
}
输出:
player1
bug
name with space
bob
或者将堆叠的迭代器转换为数组:
$array = iterator_to_array($playerIterator);
print_r($array);
输出:
Array
(
[1] => player1
[2] => bug
[3] => name with space
[4] => bob
)
答案 3 :(得分:0)
最简单的方法:
$file = file_get_contents($filepath);
$column_width = strpos($file,'Alive:') + 1;
preg_match_all('/^(.{'.$column_width.'}).*$/m', $file, $matches);
unset($matches[1][0]);
$result = array_map('trim', $matches[1]);
最终的$结果是:
array (
0 => 'player1',
1 => 'bug',
2 => 'name with space',
3 => 'bob',
),