4

I'm trying to debug a legacy php script (😪 ) designed to be run via command line. The script is designed to take 1 optional argument, followed by N options. It was written with the intention that both of the following cases should work.

Case 1: Argument with options:

php script.php <argument> --option-a=tuesdays --option-b

Case 2: No argument with options:

php script.php --option-c

Inside the script, the argument and the options are fetched using the following:

$argument = (strpos($argv[1], '-') === 0) ? '' : $argv[1];
$options = getopt('', [
  'option-a:', 
  'option-b', 
  'option-c',
]);

Case 2 always works as expected. I receive the options and the argument is empty.

Case 1 doesn't work as expected. I received the argument, but the $options array is always empty.

I've seen the suggestion that reverses the order of the options and arguments, so I'd call it via php script --option-c <argument>. I don't want to change how it's being called, since this is a legacy script that could be used goodness-knows-where.

Is there a way I could use getopt() to fetch the options that would correct Case 1?

1 Answer 1

4

I found my own answer via http://php.net/getopt. RTM.

The parsing of options will end at the first non-option found, anything that follows is discarded.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking ā€œPost Your Answerā€, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.