This question already has an answer here:
Currently I use arrays such as this one for version control of a Mysql database:
$pages_table = array (
"GUID" => array (
"type" => "CHAR(13)",
"length" => 13,
)
"Number" => array (
"type" => "TINYINT(4)",
"length" => 4,
)
"Pagename" => array (
"type" => "VARCHAR(30)",
"length" => 30,
)
It works, but I want to make it more clean, like:
$pages_table = array (
"GUID" => "CHAR(13)",
"Number" => "TINYINT(4)",
"Pagename" => "VARCHAR(30)",
);
And then if I iterate over the array, I want to set $new_length (INT) to the number between the brackets of the $new_type string:
while ($column = key($pages_table)) {
$new_type = current($pages_table);
$new_length = //Get this value from $new_type;
if ($existing_table[$column]['length'] < $new_length) {
$modify[$column] = $new_type;
}
next($pages_table);
}
</div>
Use regular expressions:
preg_match('/\(\d+\)/', $subject, $matches);
$new_length = $matches[0];
You could shorten the pattern if it is guaranteed that there are no other numbers in the string:
preg_match('/\d+/', $subject, $matches);
$new_length = $matches[0];
while ($column = key($pages_table)) {
$new_type = current($pages_table);
$hasLength = (preg_match('/\(\d+\)/', $new_type, $matches) == 1);
$new_length = intval($matches[0]);
if ($hasLength && $existing_table[$column]['length'] < $new_length) {
$modify[$column] => $new_type;
}
next($pages_table);
}
$new_length = (int) preg_replace('/\D/', '', $new_type);