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;
}
看起来很简单,但我缺乏洞察力,不知道这是否是我想做的事情的最佳实现。 也就是说,我只需要先按引号部分将字符串分解为子字符串数组,然后按空格(即在非引号部分中(。 它的意思是类似于我网站上的实际命令提示符。
洞察力赞赏。
以下是我如何处理这个项目:
1(从测试开始。例如。
isEqual(parseCommandString('hello world', ["hello", "world"]));
isEqual(parseCommandString('hello "world a"', ["hello", "world a"]));
2(让你的代码适合这些测试,然后添加更多的极端情况 - 例如,未闭合的引号。
如果您尝试构建的是真正的命令行(即 shell(,请考虑使用开源项目,例如 http://code.google.com/p/php-web-shell/
你可以
尝试python的optparse模块的这个端口:https://github.com/lelutin/php-optparse,或者这个更新的库:https://github.com/lelutin/php-options
两者都似乎非常强大,可能比从头开始编写自己的解析器更好。