我想从SQL'CREATE'查询中获取列名。
查询:
CREATE TABLE 'test' (
'col1' INT( 10 ) NOT NULL ,
'col2' VARCHAR( 50 ) NOT NULL ,
'col3' DATE NOT NULL
) ENGINE = MYISAM ;
代码:
preg_match_all("/'(.+)' (\w+)\(? ?(\d*) ?\)?/", $sql, $_matches, PREG_SET_ORDER);
输出:
Array (
[0] => Array ( [0] => 'col1\' INT( 10 ) [1] => col1\ [2] => INT [3] => 10 )
[1] => Array ( [0] => 'col2\' VARCHAR( 50 ) [1] => col2\ [2] => VARCHAR [3] => 50 )
[2] => Array ( [0] => 'col3\' DATE [1] => col3\ [2] => DATE [3] => )
)
但我需要这样简单的结果:
array(
array('INT( 10 )', 'col1'),
array('VARCHAR( 50 )', 'col2'),
array('DATE', 'col3')
);
我们将不胜感激。感谢
答案 0 :(得分:2)
$sql = <<<SQL
CREATE TABLE 'test' (
'col1' INT( 10 ) NOT NULL ,
'col2' VARCHAR( 50 ) NOT NULL ,
'col3' DATE NOT NULL
) ENGINE = MYISAM ;
SQL;
preg_match_all("/'(.+)' (\w+(?:\( ?\d* ?\))?)/", $sql, $matches, PREG_SET_ORDER);
$matches = array_map(function($array) {
return array($array[2], $array[1]);
}, $matches);
var_dump($matches);
输出
array(3) {
[0]=>
array(2) {
[0]=>
string(9) "INT( 10 )"
[1]=>
string(4) "col1"
}
[1]=>
array(2) {
[0]=>
string(13) "VARCHAR( 50 )"
[1]=>
string(4) "col2"
}
[2]=>
array(2) {
[0]=>
string(4) "DATE"
[1]=>
string(4) "col3"
}
}
答案 1 :(得分:2)
重新使用上一个答案中的现有查询:
preg_match_all("/'(.+)' ((\w+)\(? ?(\d*) ?\)?)/", $sql, $_matches, PREG_SET_ORDER);
$matches = array_map(function($v) {return array(trim($v[2]), $v[1]);}, $_matches);