PHP 从行中获取第一个单词

标签 php string

我有一个看起来像这样的文件(带有换行符和奇怪的间距):

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] ----> "鲍勃"

最佳答案

<?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]);

关于PHP 从行中获取第一个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6723347/

相关文章:

php - 如何避免SRP乱象?

c - "Program has stopped working"

python - 如何在 python 中使用价格对字符串进行格式化?

javascript - 用于匹配除逗号分隔数字以外的所有字符的正则表达式

php - 查找 MySQL 中使用索引的需要

javascript - 表单提交,就是不停刷新

PHP 使用 if 语句在一封邮件中发送多行

PHP 没有从 MySQL 查询返回正确的信息

Excel - 如何从大列表中查找通配符字符串

python - Pandas 正则表达式从第一次出现的字符向前看和向后看