0

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

3 Answers 3

2

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.

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

10 Comments

This doesn't work, I am using preg_split('^[^ ]+(?: ("[^"]+"|[^ ]+))*$',$text);
Error message: Unknown modifier ']'
If you're using a Perl compatible regex for preg_replace you need to surround the regex with delimiters, such as //
iirc all preg_ functions require the regex to be delimited - wrap the regex in / marks or some other delimiter.
Code: echo 1 2 3 Result: Array ( [0] => [1] => )
|
1

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().

1 Comment

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.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.