(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)
getopt — コマンドライン引数のリストからオプションを取得する
スクリプトに渡されたオプションをパースします。
short_options-)
で始まるオプションとして渡された内容とマッチさせます。
たとえば、オプション文字列 "x" は
-x というオプションを認識します。
a-z、A-Z および 0-9 のみを認識します。
long_options--)
で始まるオプションとして渡された内容とマッチさせます。
たとえば、longopts の要素 "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
// スクリプト example.php
$options = getopt("f:hp:");
var_dump($options);
?>shell> php example.php -fvalue -h
上の例の出力は以下となります。
array(2) {
["f"]=>
string(5) "value"
["h"]=>
bool(false)
}
例2 getopt() の例:長いオプション
<?php
// スクリプト example.php
$shortopts = "";
$shortopts .= "f:"; // 値が必須
$shortopts .= "v::"; // 値がオプション
$shortopts .= "abc"; // これらのオプションは値を受け取りません
$longopts = array(
"required:", // 値が必須
"optional::", // 値がオプション
"option", // 値なし
"opt", // 値なし
);
$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
// スクリプト 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
$rest_index = null;
$opts = getopt('a:b:', [], $rest_index);
$pos_args = array_slice($argv, $rest_index);
var_dump($pos_args);shell> php example.php -a 1 -b 2 -- test
上の例の出力は以下となります。
array(1) {
[0]=>
string(4) "test"
}