Search code examples
phpcommand-promptstring-parsing

Adding a "command prompt" to my site... is this how I should do it?


function parseCommandString( $str ) {
    $chunks = explode( '"', $str );
    $cmd = array();

    // Split the command into space-separated parameters (preserving quoted portions)
     $c = count($chunks);
    for( $i=0; $i<$c; $i++ ) {
        if( $i % 2 == 0 ) {
            if( $chunks[$i] == '' ) {
                continue;
            }

            $params = explode( ' ', $chunks[$i] );
             $pc = count($params);
            for( $j=0; $j<$pc; $j++ ) {
                if( $params[$j] != '' ) {
                    $cmd[] = $params[$j];
                }
            }
        } else {
            if( $chunks[$i] != '' ) {
                $cmd[] = $chunks[$i];
            }
        }
    }
    return $cmd;
}

Seems simple enough, but I lack insight on whether this is the best implementation for what I want to do. That is, I simply need to break apart a string into an array of substrings first by sections of quotes, then by spaces (within non-quoted sections, that is). It is meant to be like an actual command prompt on my site.

Insight appreciated.


Solution

  • Here is how I would approach this project:

    1) Start with tests. For example.

    isEqual(parseCommandString('hello world', ["hello", "world"]));
    isEqual(parseCommandString('hello "world a"', ["hello", "world a"]));
    

    2) Make your code fit those tests, and then add more corner cases - for example, unclosed quotes.

    If what you're trying to build is a true command line (i.e. a shell), consider using an open source project, ex. http://code.google.com/p/php-web-shell/