dongliehuan3925 2013-09-07 15:37
浏览 78
已采纳

如何从PHP中的字符串中的括号中获取数字[重复]

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>
  • 写回答

2条回答 默认 最新

  • doucheng7534 2013-09-07 15:39
    关注

    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);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭