Parsing command arguments in PHP

后端 未结 11 759
萌比男神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:26

    There really is no native function for parsing commands to my knowledge. However, I have created a function which does the trick natively in PHP. By using str_replace several times, you are able to convert the string into something array convertible. I don't know how fast you consider fast, but when running the query 400 times, the slowest query was under 34 microseconds.

    function get_array_from_commands($string) {
        /*
        **  Turns a command string into a field
        **  of arrays through multiple lines of 
        **  str_replace, until we have a single
        **  string to split using explode().
        **  Returns an array.
        */
    
        // replace single quotes with their related
        // ASCII escape character
        $string = str_replace("\'","'",$string);
        // Do the same with double quotes
        $string = str_replace("\\\"",""",$string);
        // Now turn all remaining single quotes into double quotes
        $string = str_replace("'","\"",$string);
        // Turn " " into " so we don't replace it too many times
        $string = str_replace("\" \"","\"",$string);
        // Turn the remaining double quotes into @@@ or some other value
        $string = str_replace("\"","@@@",$string);
        // Explode by @@@ or value listed above
        $string = explode("@@@",$string);
        return $string;
    }
    

提交回复
热议问题