【问题标题】:How to split words after = (equals) in PHP? [duplicate]如何在PHP中=(等于)之后拆分单词? [复制]
【发布时间】:2017-01-27 05:53:28
【问题描述】:

我需要在等号(=)之后拆分单词,输出如下:

servercreate virtualserver_port=5383 virtualserver_maxclients=5
sid=43 token=hXy4fvF54hMgcZTJkf6f1JcPpvkURMDiOIJ9ERqN virtualserver_port=5383
error id=0 msg=ok

我需要这个 sid=NUMBER 和 token=hXy4... 在 php 中拆分并存储在 mysql 中。

我试着和自己分手:

$sid = split("sid=", $data);
    $token = split("token=", $sid[1]);
    fclose($stream);
    $data1 = ["0" => "$sid[0]", "1" => "$token[1]"];
    return $data1;

但作为回报,我收到了这个:

TS3
Welcome to the TeamSpeak 3 ServerQuery interface, type "help" for a list of commands and "help <command>" for information on a specific command.

在 php 中基本上运行了三个带有 ssh2 功能的命令,首先是“telnet IP PORT”,输出为:

TS3
Welcome to the TeamSpeak 3 ServerQuery interface, type "help" for a list of commands and "help <command>" for information on a specific command.

下一个命令是“login ...”输出是:

error id=0 msg=ok

最新的是 ""servercreate ..." 并且输出是 sid=... token=...

【问题讨论】:

  • 使用分割函数split('=',关键字);
  • 使用explode函数explode('=',keyword);

标签: php sql regex split explode


【解决方案1】:

使用explode() 并创造性地使用php字符串函数:

$explodeOnEqualSign = explode("=", $str);
$count = count($explodeOnEqualSign);

$sid = $token = '';
for($i = 0; $i < $count; $i++) {

    $previous = $i - 1;
    if (substr($explodeOnEqualSign[$previous], -3) === 'sid') {
        $sid = strstr($explodeOnEqualSign[$count], " ", true);
    } else {
        if (substr($explodeOnEqualSign[$previous], -5) === 'token') {
            $token = strstr($explodeOnEqualSign[$count], " ", true);
        }
    }

}

return array($sid, $token);

【讨论】:

  • 进行了编辑 - 如果输出的模式始终相同,我相信这应该可以工作
【解决方案2】:

使用正则表达式:

$data = "servercreate virtualserver_port=5383 virtualserver_maxclients=5
sid=43 token=hXy4fvF54hMgcZTJkf6f1JcPpvkURMDiOIJ9ERqN virtualserver_port=5383
error id=0 msg=ok";

if (preg_match_all("/(\w+)=(\w+)/", $data, $matches)) {
    var_dump(array_combine($matches[1], $matches[2]));
}

样本输出:

array(6) {
  ["virtualserver_port"]=>
  string(4) "5383"
  ["virtualserver_maxclients"]=>
  string(1) "5"
  ["sid"]=>
  string(2) "43"
  ["token"]=>
  string(40) "hXy4fvF54hMgcZTJkf6f1JcPpvkURMDiOIJ9ERqN"
  ["id"]=>
  string(1) "0"
  ["msg"]=>
  string(2) "ok"
}

【讨论】:

    猜你喜欢
    • 2018-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-08
    • 2017-11-02
    • 1970-01-01
    • 2017-07-26
    • 1970-01-01
    相关资源
    最近更新 更多