Parsing command arguments in PHP

后端 未结 11 734
萌比男神i
萌比男神i 2020-12-11 01:19

Is there a native \"PHP way\" to parse command arguments from a string? For example, given the following string:

foo \"bar \\\"baz         


        
11条回答
  •  既然无缘
    2020-12-11 01:32

    I suggest something like:

    $str = <<\\\\\\\\)*'|\"(?:.*)(?\\\\\\\\)*\")/U", $str, null, PREG_SPLIT_DELIM_CAPTURE);
    
    var_dump(array_filter(array_map('trim', $match)));
    

    With some assistance from: string to array, split by single and double quotes for the regexp

    You still have to unescape the strings in the array after.

    array(3) {
      [0]=>
      string(3) "foo"
      [1]=>
      string(13) ""bar \"baz\"""
      [3]=>
      string(10) "'\'quux\''"
    }
    

    But you get the picture.

提交回复
热议问题