从PHP中的preg_split获取分隔符

时间:2011-07-18 11:54:10

标签: php regex

我的PHP代码:

$cmd = 'SELECT var1 FROM var2 GROUP BY var3 LIMIT var4';
// split command
$p = preg_split('/SELECT|FROM|GROUP BY|LIMIT/si', $cmd);

输出:

Array
(
  [0] =>  
  [1] =>  var1 
  [2] =>  var2 
  [3] =>  var3
  [4] =>  var4
)

下面的输出是否可能?

Array
(
  [SELECT] => var1
  [FROM] => var2
  [GROUP BY] => var3
  [LIMIT] => var4
)

有什么办法来获取分隔符吗?

4 个答案:

答案 0 :(得分:3)

您是否考虑过使用SQL解析器?这个regex-hack你肯定会得到错误的结果。

结帐:

  1. http://code.google.com/p/php-sql-parser
  2. http://pear.php.net/package/SQL_Parser
  3. PHP MySQL SQL parser (INSERT and UPDATE)
  4. 带选项1的演示:

    #!/usr/bin/env php
    <?php
    
    // http://php-sql-parser.googlecode.com/svn/trunk/php-sql-parser.php
    require_once('php-sql-parser.php');
    
    $cmd = 'SELECT var1 FROM var2 GROUP BY var3 LIMIT var4';
    $parser = new PHPSQLParser($cmd);
    $parse_tree = $parser->parsed;
    
    echo 'SELECT -> ' . $parse_tree['SELECT'][0]['base_expr'] . "\n";
    echo 'FROM   -> ' . $parse_tree['FROM'][0]['table'] . "\n";
    echo 'GROUP  -> ' . $parse_tree['GROUP'][0]['base_expr'] . "\n";
    echo 'LIMIT  -> ' . $parse_tree['LIMIT']['end'] . "\n";
    
    ?>
    

    产生

    SELECT -> var1
    FROM   -> var2
    GROUP  -> var3
    LIMIT  -> var4

答案 1 :(得分:2)

$cmd = 'SELECT var1 FROM var2 GROUP BY var3 LIMIT var4';

$array = array();
if(preg_match_all('/(SELECT|FROM|GROUP BY|LIMIT)\s+([^\s]+)/si', $cmd, $matches)) {
    $array = array_combine($matches[1], $matches[2]);
}

var_dump($array);

结果:

array
  'SELECT' => string 'var1' (length=4)
  'FROM' => string 'var2' (length=4)
  'GROUP BY' => string 'var3' (length=4)
  'LIMIT' => string 'var4' (length=4)

答案 2 :(得分:1)

尝试

$matches = array();
preg_match ('~^SELECT (?P<SELECT>.+) FROM (?P<FROM>.+) GROUP BY (?P<GROUPBY>.+) LIMIT (?P<LIMIT>.+)~', $cmd, $matches);
  

或者有没有办法获得分隔符?

正则表达式总是以分隔符开头(因为它反过来:第一个字符定义分隔符)

echo $regEx[0];

答案 3 :(得分:1)

有点凌乱......

//echo file_get_contents('http://wp.me/pbZy8-1WM');
$cmd = 'SELECT var1 FROM var2 GROUP BY var3 LIMIT var4';
// split command
$pattern = 'SELECT|FROM|GROUP BY|LIMIT';
$p = preg_split('/('.$pattern.')/si', $cmd, null,PREG_SPLIT_DELIM_CAPTURE);
foreach($p as $i => $str)
if (strpos($pattern,$str) !== false)
{
    $rez[$str] = $p[$i+1];
} 
var_dump($rez);

给出:

  'SELECT' => string ' var1 ' (length=6)
  'FROM' => string ' var2 ' (length=6)
  'GROUP BY' => string ' var3 ' (length=6)
  'LIMIT' => string ' var4' (length=5)