解析字符串以解析字符串中的命令行参数?

时间:2016-04-09 03:28:00

标签: php string

是否存在本地" PHP方式"从字符串解析命令参数?例如,给定以下字符串:

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

我想创建以下数组:

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

所以标志被定义为" - "并且标志后面的字符串确定属性及其对应的值。

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

1 个答案:

答案 0 :(得分:0)

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

$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
);
相关问题