拆分包含单词和数字的字符串

时间:2017-01-17 23:25:55

标签: php

我有一个体育比分。我需要将它分成团队和分数,但问题是有时团队的名字中有多个单词:

$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';

2 个答案:

答案 0 :(得分:0)

试试这个

  $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 )

答案 1 :(得分:0)

使用preg_match_all函数的解决方案:

$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
)