I have a sports score. I need to split it up into teams and scores, but the problem is sometimes teams have more than one word in their names for instance:
$str = "New Mexico State 75 Alabama 84 FINAL";
I have tried things like:
$arr= preg_split("/[\s]+/", $str);
Which just splits by space, which is not what I want. I need the output to be:
$arr[0] = 'New Mexico State';
$arr[1] = '75';
$arr[2] = 'Alabama';
$arr[3] = '84';
Try this
$str = "New Mexico State 75 Alabama 84 FINAL";
$arr= preg_split('/(?<=\D)(?=\d)|\d+\K/', $str);
print_r($arr);
this will output
Array ( [0] => New Mexico State [1] => 75 [2] => Alabama [3] => 84 [4] => FINAL )
The solution using preg_match_all
function:
$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);
The output:
Array
(
[0] => New Mexico State
[1] => 75
[2] => Alabama
[3] => 84
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.