drtiwd06558 2019-03-14 00:20 采纳率: 100%
浏览 247
已采纳

如何在PHP中将数字与数字分开

I have string as following:

$str = "Q1-Q4,A3-A6,S9-S11";

Can someone tell me how to split the above text in PHP so that I get following as output:

Q1,Q2,Q3,Q4,A3,A4,A5,A6,S9,S10,S11

  • 写回答

2条回答 默认 最新

  • doubi8965 2019-03-14 01:26
    关注

    This should get you going. This separates the sequences, adds in extra items and returns all of this as an array you can conveniently use.

    $str = "Q1-Q4,A3-A6,S9-S11";
    
    $ranges = explode (',', $str);
    $output = [];
    
    foreach ($ranges as $range) {
    
        $items = explode ('-', $range );
        $arr = [];
        $fillin = [];
    
        $letter = preg_replace('/[^A-Z]/', '', $items[0]);
        $first  = preg_replace('/[^0-9]/', '', $items[0]);
        $last   = preg_replace('/[^0-9]/', '', end($items));
    
    
        for($i = $first; $i-1 < $last; $i++) {
            $fillin[] = $letter . $i;
        }
    
        $output[]  = $fillin;
    
    }
    
    var_dump( $output );
    exit;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?