Reputation: 18560
I want to get column names from SQL 'CREATE' query.
Query:
CREATE TABLE 'test' (
'col1' INT( 10 ) NOT NULL ,
'col2' VARCHAR( 50 ) NOT NULL ,
'col3' DATE NOT NULL
) ENGINE = MYISAM ;
Code:
preg_match_all("/'(.+)' (\w+)\(? ?(\d*) ?\)?/", $sql, $_matches, PREG_SET_ORDER);
Output:
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] => )
)
But I need simple result like this:
array(
array('INT( 10 )', 'col1'),
array('VARCHAR( 50 )', 'col2'),
array('DATE', 'col3')
);
Every possible solution will be appreciated. Thanks
Upvotes: 2
Views: 182
Reputation: 197767
Re-using the existing query from the previous answer:
preg_match_all("/'(.+)' ((\w+)\(? ?(\d*) ?\)?)/", $sql, $_matches, PREG_SET_ORDER);
$matches = array_map(function($v) {return array(trim($v[2]), $v[1]);}, $_matches);
Upvotes: 2
Reputation: 222158
$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);
Output
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"
}
}
Upvotes: 2