PHP命令行:使用argv和getopt不起作用



尝试使用argv变量和getopt()似乎不起作用。有人知道除了使用全-或——选项之外的其他工作吗:

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

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

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

Hello World

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

没有输出,因为我放置了一个没有-或——的值

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;
}

这有点蛮力,但它更好地解决了我的相关问题。根据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
}

最新更新