【问题标题】:How to get number from between brackets in string in PHP [duplicate]如何从PHP中字符串中的括号之间获取数字[重复]
【发布时间】:2013-09-11 13:38:24
【问题描述】:

目前我使用这样的数组来控制 Mysql 数据库的版本:

$pages_table = array (
    "GUID" => array (
        "type" => "CHAR(13)",
        "length" => 13,
    )
    "Number" => array (
        "type" => "TINYINT(4)",
        "length" => 4,
    )
    "Pagename" => array (
        "type" => "VARCHAR(30)",
        "length" => 30,
    )

它可以工作,但我想让它更干净,比如:

$pages_table = array (
    "GUID" => "CHAR(13)",
    "Number" => "TINYINT(4)",
    "Pagename" => "VARCHAR(30)",
);

然后,如果我遍历数组,我想将 $new_length (INT) 设置为 $new_type 字符串括号之间的数字:

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);
}

【问题讨论】:

  • @Itay:它是括号之间的整数,而不是字符串。所以他们的回答并不是 100% 符合我的需要。虽然正则表达式部分是相同的,但我也不知道首先使用正则表达式,因为那个提问者有一个真正的正则表达式问题。

标签: php mysql regex


【解决方案1】:

使用正则表达式:

preg_match('/\(\d+\)/', $subject, $matches);
$new_length = $matches[0];

如果保证字符串中没有其他数字,则可以缩短模式:

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);
}

【讨论】:

  • $subject 需要$new_type 那么?否则无法确定$subject 的来源。
  • @Tim 抱歉,我忘记更新名称了。是的,它是$new_type
  • @Tim 您的编辑被拒绝,因为它添加了更多代码。编辑用于更正现有代码或改进语法/拼写。几秒钟前我自己编辑了这篇文章,以包含您编辑的一些想法;)
【解决方案2】:
$new_length = (int) preg_replace('/\D/', '', $new_type);

【讨论】:

  • 好的,我现在知道了。我仍然认为 preg_match 选项更具可读性。
猜你喜欢
  • 2012-07-15
  • 1970-01-01
  • 2015-10-16
  • 1970-01-01
  • 1970-01-01
  • 2016-03-24
  • 1970-01-01
  • 2014-05-12
  • 2013-02-04
相关资源
最近更新 更多