我有一个看起来像这样的文件(带有换行符和奇怪的间距):
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
Run Code Online (Sandbox Code Playgroud)
如何抓住第一列并将其转换为数组?
期望的输出:
$ players [1] ---->"player1"
$ players [2] ---->"bug"
$ players [3] ---->"with space with space"
$ players [4] - --->"鲍勃"
<?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]);
Run Code Online (Sandbox Code Playgroud)
对于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]);
Run Code Online (Sandbox Code Playgroud)