php cli:使用argv和getopt不起作用

问题描述 投票:0回答:2

尝试使用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”

无输出,因为我在其前面没有-或-的值。

php command-line-interface argv getopt
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;
}

0
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.