我怎样才能通过爆炸只获取一些特定的数据?

How can i take only some specific data by explode?

在我的以下代码中,我可以分解并获取我的 3 个元素 imei、lat、lon,因为响应仅返回由 ' ' 分隔的 3 个数据。

   $r = socket_recvfrom($sock, $buf, 512, 0, $remote_ip, $remote_port);
    echo "$remote_ip : $remote_port -- " . $buf;

    list($imei,$lat,$lon) = explode(' ', $buf, 3); 

但是,如果响应向我发送大量由 ' ' 分隔的数据怎么办,但我仍然只需要 3 个元素。我不需要其余数据。我怎么会爆炸成那样?

数据不会是explode()返回的前三项。

只需在 list() 中再添加一个逗号即可忽略其余值:

list($imei,$lat,$lon,) = explode(' ', $buf); 

Demo

或者,如果值位于数组中的特定位置:

list($imei, , $lat, , $lon,) = explode(' ', $buf); 

Demo

空占位符 "skip" 这些值,它们永远不会分配给变量。

其实你什么都不用做。如果分解后的数组中有多余的元素,list 不会在意。

参见:

$string = "a b c d e f";
list($a,$b,$c) = explode(' ',$string);

作为@John 回答的扩展,还有另一个 php 函数 strtok() 在这种情况下很有用

$imei = strtok($buf, ' ');
$lat = strtok(' ');
$lon = strtok(' ');

现在,假设你的字符串

$buf = 'test1 test2 test3 test4 test5';

$imei,$lat,$lon会,

string 'test1' (length=5)
string 'test2' (length=5)
string 'test3' (length=5)

来自 php.net 手册页,

Note that only the first call to strtok uses the string argument. Every subsequent call to strtok only needs the token to use, as it keeps track of where it is in the current string. To start over, or to tokenize a new string you simply call strtok with the string argument again to initialize it. Note that you may put multiple tokens in the token parameter. The string will be tokenized when any one of the characters in the argument are found.