(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)
getopt — 从命令行参数列表中获取选项
$short_options, array $long_options = [], int &$rest_index = null): array|false解析传入脚本的选项。
short_options-) 开头。
比如,一个选项字符串 "x" 识别了一个选项
-x。
只允许 a-z、A-Z 和 0-9。
long_options--) 传入到脚本的选项。
例如,长选项元素 "opt" 识别了一个选项
--opt。
rest_indexrest_index
参数,那么参数解析停止时的索引,将被赋值给此变量。
short_options 可能包含了以下元素:
注意: 选项的值不接受空格(
" ")作为分隔符。
long_options 数组可能包含了以下元素:
注意:
short_options和long_options的格式几乎是一样的,唯一的不同之处是long_options需要是选项的数组(每个元素为一个选项),而short_options需要一个字符串(每个字符是个选项)。
此函数会返回选项/参数对, 或者在失败时返回 false。
注意:
选项的解析会终止于找到的第一个非选项,之后的任何东西都会被丢弃。
| 版本 | 说明 |
|---|---|
| 7.1.0 |
添加 rest_index 参数。
|
示例 #1 getopt() 例子:基本用法
<?php
// Script example.php
$rest_index = null;
$opts = getopt('a:b:', [], $rest_index);
$pos_args = array_slice($argv, $rest_index);
var_dump($pos_args);
shell> php example.php -fvalue -h
以上例程会输出:
array(2) {
["f"]=>
string(5) "value"
["h"]=>
bool(false)
}
示例 #2 getopt() 例子:引入长选项
<?php
// Script example.php
$shortopts = "";
$shortopts .= "f:"; // Required value
$shortopts .= "v::"; // Optional value
$shortopts .= "abc"; // These options do not accept values
$longopts = array(
"required:", // Required value
"optional::", // Optional value
"option", // No value
"opt", // No value
);
$options = getopt($shortopts, $longopts);
var_dump($options);
?>
shell> php example.php -f "value for f" -v -a --required value --optional="optional value" --option
以上例程会输出:
array(6) {
["f"]=>
string(11) "value for f"
["v"]=>
bool(false)
["a"]=>
bool(false)
["required"]=>
string(5) "value"
["optional"]=>
string(14) "optional value"
["option"]=>
bool(false)
}
示例 #3 getopt() 例子:传递同一多个选项
<?php
// Script example.php
$options = getopt("abc");
var_dump($options);
?>
shell> php example.php -aaac
以上例程会输出:
array(2) {
["a"]=>
array(3) {
[0]=>
bool(false)
[1]=>
bool(false)
[2]=>
bool(false)
}
["c"]=>
bool(false)
}
示例 #4 getopt() 例子:使用 rest_index
<?php
// Script example.php
$optind = null;
$opts = getopt('a:b:', [], $optind);
$pos_args = array_slice($argv, $optind);
var_dump($pos_args);
shell> php example.php -a 1 -b 2 -- test
以上例程会输出:
array(1) {
[0]=>
string(4) "test"
}