-1

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);
}
Tim
  • 1,585
  • 1
  • 18
  • 23
  • @Itay: It is about an integer number between brackets, not string. So their answer does not 100% fit my needs. Though the regex part is the same, I also did not know to use regex in the first place, as that questioner had a real regex question. – Tim Sep 08 '13 at 09:23

2 Answers2

2
$new_length = (int) preg_replace('/\D/', '', $new_type);
rid
  • 61,078
  • 31
  • 152
  • 193
2

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);
}
ComFreek
  • 29,044
  • 18
  • 104
  • 156
  • `$subject` need to be `$new_type` then? Can't figure where `$subject` is coming from otherwise. – Tim Sep 07 '13 at 15:58
  • @Tim Sorry, I forgot to update the names. Yes, it is `$new_type`. – ComFreek Sep 07 '13 at 16:00
  • @Tim Your edit got rejected because it added more code. Edits are for corrections of already existing codes or of improvements of grammar/spelling. I edited the post myself a few seconds ago in order to include some ideas of your edit ;) – ComFreek Sep 08 '13 at 13:26