【问题标题】:Parse a string to parse command line arguments from a string?解析字符串以解析字符串中的命令行参数?
【发布时间】:2016-07-30 11:18:56
【问题描述】:

是否有一种原生的“PHP 方式”来解析字符串中的命令参数?例如,给定以下字符串:

some random string --color=red --is_corvette=true

我想创建以下数组:

array(3) { ['color'] => string(3) "red" ['is_corvette'] => string(4) "true" }

所以一个标志被定义为“--”,标志后面的字符串决定了属性及其对应的值。

我知道 PHP 的 getopt() 函数,但它似乎只能用于解析通过命令行传递给 PHP 脚本的参数,并且似乎无法按需解析任何字符串

【问题讨论】:

  • 这可以通过相当容易地标记字符串来完成
  • 你可以使用 PEAR 的Console_Getopt 类。它类似于getopt,但接受字符串。

标签: php string


【解决方案1】:

您可以使用正则表达式查找每个匹配项,然后重新格式化其结果以获得您期望的结果,如下所示:

$s = 'some random string --color=red --is_corvette=true';
preg_match_all(
  '/--((?:color|is_corvette)=[\S]+)/',
  $s, $matches
);
if ($matches AND $matches[1]) {
  foreach ($matches[1] AS $match) {
    $match = explode('=', $match);
    $result[$match[0]] = $match[1];
  }
}

除了当前示例之外,您还可以构建一个更通用的函数,同时考虑一组预定义的可能键及其默认值:

function args_from_string($string, $set) {
    preg_match_all(
      '/--((?:' . implode('|', array_keys($set)) . ')=[\S]+)/',
      $string, $matches
    );
    if ($matches AND $matches[1]) {
      foreach ($matches[1] AS $match) {
        $match = explode('=', $match);
        $set[$match[0]] = $match[1];
      }
    }
    return $set;
}

$predefined_set = [
    'color'       => 'black',
    'is_corvette' => 'false',
    'other_arg'   => 'value',
    // ...
];
$current_set = args_from_string(
    'some random string --color=red --is_corvette=true',
    $predefined_set
);

【讨论】:

    猜你喜欢
    • 2019-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-07
    • 1970-01-01
    • 2023-04-06
    • 2016-12-10
    • 1970-01-01
    相关资源
    最近更新 更多