preg_match捕获两个大写字母,3个数字和2个大写字母,而不是7个数字

时间:2014-08-18 00:33:10

标签: php

好的,我有以下字符串

“IG 449WW 6180262 250”

我希望匹配前两个字母,而不是第二个5个字母和数字,而不是7个数字,我想要捕获每个字母。

所以我有以下preg_match:

  $scanned_barcode = trim(Input::get('barcode'));

    if (preg_match("/([A-Z]{2})\s(\d{3}[A-Z]{2})\s(\d{7})/", $scanned_barcode, $found)) {
        $mfg_id    = $found[1];
        $game_code = $found[2];
        $serial    = Game::find($found[3]);
}

我这样做是对的吗?有什么我想念的吗?有更好的方法吗?

1 个答案:

答案 0 :(得分:0)

你的正则表达式有效,但这样做会更容易:

<?php

    $scanned_barcode = trim(Input::get('barcode'));

    // 'explode' the string into an array(), using the space as the delimiter
    // http://php.net/manual/en/function.explode.php
    $found = explode(' ', $scanned_barcode);

    $mfg_id    = $found[0];
    $game_code = $found[1];
    $serial    = Game::find($found[2]);

?>