Parsing command arguments in PHP

后端 未结 11 738
萌比男神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条回答
  •  萌比男神i
    2020-12-11 01:47

    If you want to follow the rules of such parsing that are there as well as in shell, there are some edge-cases which I think aren't easy to cover with regular expressions and therefore you might want to write a method that does this (example):

    $string = 'foo "bar \"baz\"" \'\\\'quux\\\'\'';
    echo $string, "\n";
    print_r(StringUtil::separate_quoted($string));
    

    Output:

    foo "bar \"baz\"" '\'quux\''
    Array
    (
        [0] => foo
        [1] => bar "baz"
        [2] => 'quux'
    )
    

    I guess this pretty much matches what you're looking for. The function used in the example can be configured for the escape character as well as for the quotes, you can even use parenthesis like [ ] to form a "quote" if you like.

    To allow other than native bytesafe-strings with one character per byte you can pass an array instead of a string. the array needs to contain one character per value as a binary safe string. e.g. pass unicode in NFC form as UTF-8 with one code-point per array value and this should do the job for unicode.

提交回复
热议问题