Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Grab first word from line

Tags:

string

php

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      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"

like image 388
dukevin Avatar asked Dec 27 '22 17:12

dukevin


1 Answers

<?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]);
like image 56
RiaD Avatar answered Dec 30 '22 11:12

RiaD