2017-01-17 92 views
1

我有一個體育比分。我需要它分成小組和分數,但問題是有時團隊有超過一個字在他們的名字,例如:分割包含單詞和數字的字符串

$str = "New Mexico State 75 Alabama 84 FINAL"; 

我曾嘗試喜歡的東西:

$arr= preg_split("/[\s]+/", $str); 

剛剛按空間分割,這不是我想要的。我需要的輸出爲:

$arr[0] = 'New Mexico State'; 
$arr[1] = '75'; 
$arr[2] = 'Alabama'; 
$arr[3] = '84'; 

回答

0

使用preg_match_all功能試試這個

$str = "New Mexico State 75 Alabama 84 FINAL"; 
    $arr= preg_split('/(?<=\D)(?=\d)|\d+\K/', $str); 
    print_r($arr); 

這將輸出

Array ([0] => New Mexico State [1] => 75 [2] => Alabama [3] => 84 [4] => FINAL) 
+0

這就是那個..謝謝! – xar86413

+0

沒問題,如果你不介意接受那真棒的答案。 下面是如何** [鏈接](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)**然後返回這裏,並做同樣的勾號/選中標記它變成綠色。 –

0

解決辦法:

$str = "New Mexico State 75 Alabama 84 FINAL"; 
preg_match_all("/(\D+)((?:\d+\b))/", $str, $matches, PREG_SET_ORDER); 

$result = []; 
foreach ($matches as $m) { 
    $result[] = trim($m[1]); 
    $result[] = $m[2]; 
} 

print_r($result); 

輸出:

Array 
(
    [0] => New Mexico State 
    [1] => 75 
    [2] => Alabama 
    [3] => 84 
)