0

尝试使用 argv 变量和 getopt() 似乎不起作用。任何人都知道除了使用所有 - 或 - 选项之外的解决方法:

<?php
$arr[] = "test:";
$options = getopt(NULL, $arr);
echo $options["test"];
?>

上面的简单示例,当我运行时:

php test.php --test="Hello World"

你好世界

php test.php argv --test="Hello World"

没有输出,因为我在它之前放置了一个没有 - 或 - 的值。

4

2 回答 2

1
function get_opt() {
    $options = array();
    foreach( $_SERVER[ "argv" ] as $key => $arg ) {
        if ( preg_match( '@\-\-(.+)=(.+)@', $arg, $matches ) ) {
            $key   = $matches[ 1 ];
            $value = $matches[ 2 ];
            $options[ $key ] = $value;
        } else if ( preg_match( "@\-(.)(.)@", $arg, $matches ) ) {
            $key   = $matches[ 1 ];
            $value = $matches[ 2 ];
            $options[ $key ] = $value;
        }
    }
    return $options;
}
于 2014-02-13T19:19:57.923 回答
1

这有点蛮力,但它更好地解决了我的相关问题。根据 user3307546 的回答:

function get_opts() {
    $opts = array();
    foreach($_SERVER["argv"] as $k => $a){
        if(preg_match( '@\-\-(.+)=(.+)@'  , $a, $m))
            $opts[$m[1]] = $m[2];
        elseif(preg_match( '@\-\-(.+)@'   , $a, $m))
            $opts[$m[1]] = true;
        elseif(preg_match( '@\-(.+)=(.+)@', $a, $m))
            $opts[$m[1]] = $m[2];
        elseif(preg_match( '@\-(.+)@'     , $a, $m))
            $opts[$m[1]] = true;
        else
            $opts[$k] = $a;
    }
    return $opts;
}

所以

> php cli/index.php gen/cache/reports -e --refresh-api -s="2020-04-16" -v

被解析为

{
    0: "cli/index.php",
    1: "ttd/cache/reports",
    "e": true,
    "refresh-api": true,
    "s": "2020-04-16",
    "v": true
}

所有“非选项”都以其在哈希键中的序号位置出现。

于 2020-04-16T20:05:12.540 回答