$value ) { if ( count($value) == 1 ) $options[$key] = $value[0]; } return $options; } /** * split parameters * * static helper function * * @version 1.0 * @date 2008/08/19 * @see http://www.ntu.beautifulworldco.com/weblog/?p=526 * * This function is to parse parameters and split them into smaller pieces. * preg_split() does similar thing but in our function, besides "space", we * also take the three symbols " (double quote), '(single quote), * and \ (backslash) into consideration because things in a pair of " or ' * should be grouped together. * * As an example, this parameter list * * -f "test 2" -ab --required "t\"est 1" --optional="te'st 3" --option -v 'test 4' * * will be splited into * * -f; test 2; -ab; --required; t"est 1; --optional=te'st 3; --option; -v; test 4 * * see the code below: * * * $pattern = "-f \"test 2\" -ab --required \"t\\\"est 1\" --optional=\"te'st 3\" --option -v 'test 4'"; * $result = getoptParser::split_para($pattern); * echo "ORIGINAL PATTERN: $pattern\n\n"; * var_dump($result); * * * @param string $pattern * @return array */ public static function split_para($pattern) { $begin = 0; $backslash = 0; $quote = ''; $quote_mark = array(); $result = array(); $pattern = trim($pattern); $cand1 = ''; for ( $end = 0; $end < strlen($pattern); ) { if ( !in_array($pattern[$end], array(' ', '"', "'", "\\")) ) { $backslash = 0; $end++; continue; } if ( $pattern[$end] == "\\" ) { $backslash++; $end++; continue; } elseif ( $pattern[$end] == '"' ) { if ( $backslash % 2 == 1 || $quote == "'" ) { $backslash = 0; $end++; continue; } if ( $quote == '' ) { $quote_mark[] = $end - $begin; $quote = '"'; } elseif ( $quote == '"' ) { $quote_mark[] = $end - $begin; $quote = ''; } $backslash = 0; $end++; continue; } elseif ( $pattern[$end] == "'" ) { if ( $backslash % 2 == 1 || $quote == '"' ) { $backslash = 0; $end++; continue; } if ( $quote == '' ) { $quote_mark[] = $end - $begin; $quote = "'"; } elseif ( $quote == "'" ) { $quote_mark[] = $end - $begin; $quote = ''; } $backslash = 0; $end++; continue; } elseif ( $pattern[$end] == ' ' ) { if ( $quote != '' ) { $backslash = 0; $end++; continue; } else { $backslash = 0; $cand = substr($pattern, $begin, $end-$begin); for ( $j = 0; $j < strlen($cand); $j++ ) { if ( in_array($j, $quote_mark) ) continue; $cand1 .= $cand[$j]; } if ( $cand1 ) { // commented and replaced: // eval( "\$cand1 = \"$cand1\";" ); $result[] = (string) $cand1; } $quote_mark = array(); $cand1 = ''; $begin =++$end; continue; } } } $cand = substr($pattern, $begin, $end-$begin); for ( $j = 0; $j < strlen($cand); $j++ ) { if ( in_array($j, $quote_mark ) ) continue; $cand1 .= $cand[$j]; } // commented and replaced: // eval( "\$cand1 = \"$cand1\";" ); $cand1 = (string) $cand1; if ( $cand1 ) $result[] = $cand1; return $result; } } ?>