Panwen Wang Panwen Wang - 1 year ago 134
PHP Question

Get $argv from a string with PHP

We know that can easily get the argument array from the command line with the predefined variable


Is there any easy way to get the array from a string instead of the command line ?

I need to write some tests for related library.

For example, when you run
script.php -a b -c d
, in

you could get
with value
["script.php", "-a", "b", "-c", "d"]

So here my question is that, inside a php script,

how can I get this array from a string, say
"-a b -c d"
here not by passing the string to the command line but to a variable ?

I don't need to parse the options here.

The most simple way to do is:

$array = preg_split ("/\s+/", $str);

However, this cannot cover the strings with spaces inside the option value.


-a "some thing"

Answer Source

Ok, Nobody answered this, I would propose one solution here:

function getArgv ($string) {
    global $argv;
    preg_match_all ('/(?<=^|\s)([\'"]?)(.+?)(?<!\\\\)\1(?=$|\s)/', $string, $ms);
    $argv = $ms[2];

getArgv("-a b -c d");
print_r ($argv);
getArgv('-a \'b  -c d\' -c "da  fwe\" a" awf="sadf"');
print_r ($argv);


    [0] => -a
    [1] => b
    [2] => -c
    [3] => d
    [0] => -a
    [1] => b  -c d
    [2] => -c
    [3] => da  fwe\" a
    [4] => awf="sadf"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download