tags:

views:

68

answers:

3

I would like to know how to split this string:
command arg1 arg2 arg3
In this array:

[arg1,arg2,arg3]

BUT if the user types:
command "arg1 still arg1" arg2
The array will be:

[arg1 still arg1, arg2]

Using PHP

+1  A: 

Use a regular expression like this:

^[^ ]+(?: ("[^"]+"|[^ ]+))*$

The expression "[^"]+"|[^ ]+ matches either an argument that starts and ends with a quotation mark, or an argument that ends at the next space.

Guffa
This doesn't work, I am using preg_split('^[^ ]+(?: ("[^"]+"|[^ ]+))*$',$text);
M28
Error message: Unknown modifier ']'
M28
If you're using a Perl compatible regex for `preg_replace` you need to surround the regex with delimiters, such as //
pavium
iirc all `preg_` functions require the regex to be delimited - wrap the regex in `/` marks or some other delimiter.
Amber
Code:echo 1 2 3Result:Array( [0] => [1] => )
M28
Read the definition of `preg_replace` in the online documentation: http://au.php.net/manual/en/function.preg-replace.php
pavium
I don't want to use preg_replace, I want to use preg_split.
M28
Or preg_split (as the case may be). I'm thinking of the description of the parameter which contains a perl regular expression.
pavium
I am using:$params=preg_split('/^[^ ]+(?: ("[^"]+"|[^ ]+))*$/',$full);But print_r($params); returns:Array( [0] => [1] => )
M28
Testing it here: http://www.regextester.com/ Don't give the desired result too.
M28
I have tested it in Rad Software Regular Expression Designer, and it works just fine. The first group contains captures for all the arguments.
Guffa
A: 

I believe you might want to use something like strtok for this in php, rather than a regex.

See this comment on the documentation: http://www.php.net/manual/en/function.strtok.php#94463

Paul Huff
strtok doesn't work as intend.
M28
+1  A: 

PHP does what you ask automatically.

I have PHP 5.3, and calling this code

<?php
  print $argc . "\n";

  for ($i = 0; $i < $argc; $i++) {
    print $argv[$i] . "\n";
  }
?>

with php ./argv.php Test "Test 23" "Test 34", I obtain the following output

sunradio:~ kiamlaluno$ php ./argv.php Test "Test 23" "Test 34"
4
./argv.php
Test
Test 23
Test 34
sunradio:~ kiamlaluno$

Taking off the first argument, $argv contains all the arguments as you want them. That can be easily done with array_pop().

kiamlaluno
I changed the code to use `$argc` (I use those variables very rarely, that I always forget about `$argc`).I interpreted that you meant to parse the arguments passed to PHP when executed from CLI.
kiamlaluno