2

所以这是场景,我有以下字符串:

    Detroit 7 Chicago 13 (FINAL)

我希望它返回一个数组,如下所示:

    array() { 
     ["T1_Name"]=>"Detroit" 
     ["T1_Score"]=>"7"
     ["T2_Name"]=>"Chicago" 
     ["T2_Score"]=>"13"
     ["Quarter"]=>"FINAL"
    }

诀窍是它不能用空格分隔,因为城市名称中有空格,分数也可能是一位或两位数。

4

2 回答 2

1
$subject = 'Detroit 7 Chicago 13 (FINAL)';
$matches = array();
if (preg_match('~^(.+) ([0-9]{1,2}) (.+) ([0-9]{1,2}) \((.+)\)$~i', $subject, $matches)) {
    var_dump($matches);
    $result = array(
        'T1_Name'  => $matches[1],
        'T1_Score' => $matches[2],
        'T2_Name'  => $matches[3],
        'T2_Score' => $matches[4],
        'Quarter'  => $matches[5],
    );
}
var_dump($result);

应该这样做。

于 2012-10-24T08:09:03.997 回答
0

PHP 预匹配

大概是这样的?

preg_match('/([a-zA-Z\s]+?)[\s]+([\d]+)([a-zA-Z\s]+?)[\s]+([\d]+)[\s]+\(([\w]+)\)/', "Detroit 7 Chicago 13 (FINAL)", $matches);
print_r($matches);
于 2012-10-24T08:06:01.770 回答