PHP grab the first word from a string

I have a file that looks like this (with newline and weird spacing):

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 

How can I grab the first column and turn it into an array?

Desired Result :
$ players [1] ----> "player1"
$ players [2] ----> "bug"
$ players [3] ----> "name with space"
$ players [4] ----> "bob"

+4
source share
4 answers

Here is the iterator approach:

 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 as follows:

 $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) ); 

Then you can foreach on an iterator, for example.

 foreach ($playerIterator as $player) { echo $player, PHP_EOL; } 

Output:

 player1 bug name with space bob 

Or convert the folded iterators to an array:

 $array = iterator_to_array($playerIterator); print_r($array); 

Output:

 Array ( [1] => player1 [2] => bug [3] => name with space [4] => bob ) 

Demo of the above examples with your file data

+1
source
 <?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]); 
+6
source

Another option using regex might look like this:

 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 regular expression solution, if the above looks like magic, please do not use it. There is absolutely no copy and paste of the regular expression in your code unless you know what it is actually trying to match.

+3
source

The easiest 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]); 

Final $ result:

 array ( 0 => 'player1', 1 => 'bug', 2 => 'name with space', 3 => 'bob', ), 
0
source

All Articles