2010-07-10 45 views
0

BC1024,AB124,CBC2548,pregmatch單獨的號碼和字符

使用預浸匹配以分離我想這預浸匹配表達式的數字和字符,

對於這一點,但其不大大工作,

 
preg_match_all('/(?P\w+): (?P\d+)/', $flight_code_no, $matches,PREG_PATTERN_ORDER); 

我想輸出

 
Array 
(
    [0] => BC1024: 2008 
    [name] => BC 
    [1] => BC 
    [digit] => 1024 
    [2] => 1024 
) 

但我的預浸比賽不工作... 。

只是shoing空數組,

回答

2
preg_match('/(?<name>[A-Z]+)(?<digit>\d+)/', 'BC1024', $result); 

這給出

 
Array 
(
    [0] => BC1024 
    [name] => BC 
    [1] => BC 
    [digit] => 1024 
    [2] => 1024 
) 
1

運行

<?php 

foreach (array("BC1024", "AB124","CBC2548") as $v) { 
    preg_match_all("/(?P<name>[A-Z]+)(?P<digit>\d+)/", $v, $matches); 
    var_dump($matches); 
} 

輸出(一些換行符爲brewity移除)

array(5) { 
    [0]=>  array(1) { [0]=> string(6) "BC1024" } 
    ["name"]=> array(1) { [0]=> string(2) "BC" } 
    [1]=>  array(1) { [0]=> string(2) "BC" } 
    ["digit"]=> array(1) { [0]=> string(4) "1024" } 
    [2]=>  array(1) { [0]=> string(4) "1024" } 
} 
array(5) { 
    [0]=>  array(1) { [0]=> string(5) "AB124" } 
    ["name"]=> array(1) { [0]=> string(2) "AB" } 
    [1]=>  array(1) { [0]=> string(2) "AB" } 
    ["digit"]=> array(1) { [0]=> string(3) "124" } 
    [2]=>  array(1) { [0]=> string(3) "124" } 
} 
array(5) { 
    [0]=>  array(1) { [0]=> string(7) "CBC2548" } 
    ["name"]=> array(1) { [0]=> string(3) "CBC" } 
    [1]=>  array(1) { [0]=> string(3) "CBC" } 
    ["digit"]=> array(1) { [0]=> string(4) "2548" } 
    [2]=>  array(1) { [0]=> string(4) "2548" } 
} 
2

只是爲了表明您不需要preg_match來分割像這樣的簡單字符串:

list($name,$digit) = sscanf($flight_code_no,'%[A-Z]%d');