I have a file that looks like this (with newlines and weird spacing):
Player: Alive: Score: Ping: Member of Team:
player1 No 16 69 dogs
bug Yes 2 开发者_C百科 63 insects
name with space No 0 69 cats
bob No 0 69 dogs
How can I grab the first column and turn it into an array?
Desired Output:
$players[1] ----> "player1" $players[2] ----> "bug" $players[3] ----> "name with space" $players[4] ----> "bob"<?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]);
For 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]);
Another option using a regex could look like:
preg_match_all('/^.{0,15}?(?= {2}|(?<=^.{15}))/m', $subject, $matches);
$players = $matches[0];
unset($players[0]); // remove header
var_export($players);
The resulting $players
array looks like
array (
1 => 'player1',
2 => 'bug',
3 => 'name with space',
4 => 'bob',
)
Note: As with any regex-based solution, if the above looks like magic then please don't use it. There is absolutely no point copying and pasting a regular expression into your code if you've no clue what it is actually trying to match.
Here is an approach with Iterators:
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);
}
}
You would use it like this:
$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)
);
You can then foreach
over the iterator, e.g.
foreach ($playerIterator as $player) {
echo $player, PHP_EOL;
}
Output:
player1
bug
name with space
bob
Or transform the stacked Iterators into an array:
$array = iterator_to_array($playerIterator);
print_r($array);
Output:
Array
(
[1] => player1
[2] => bug
[3] => name with space
[4] => bob
)
Demo of above examples with your file's data
The simplest way:
$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]);
The final $result is:
array (
0 => 'player1',
1 => 'bug',
2 => 'name with space',
3 => 'bob',
),
精彩评论