将带数字的长字符串转换为数组

Ita*_*nor 1 php regex arrays explode preg-split

我正在寻找一种方法将字符串1 hello there 6 foo 37 bar转换成数组,如:

Array ( [1] => "hello there",
        [6] => "foo",
        [37] => "bar" )
Run Code Online (Sandbox Code Playgroud)

每个数字都是它后面的字符串的索引.我想得到它的帮助.谢谢!:)

Rom*_*est 6

解决方案使用preg_match_allarray_combine功能:

$str = '1 hello there 6 foo 37 bar';
preg_match_all('/(\d+) +(\D*[^\s\d])/', $str, $m);
$result = array_combine($m[1], $m[2]);

print_r($result);
Run Code Online (Sandbox Code Playgroud)

输出:

Array
(
    [1] => hello there 
    [6] => foo 
    [37] => bar
)
Run Code Online (Sandbox Code Playgroud)