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

Turn a long string with numbers to array

我正在寻找一种方法将 1 hello there 6 foo 37 bar 之类的字符串转换为如下数组:

Array ( [1] => "hello there",
        [6] => "foo",
        [37] => "bar" )

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

这应该可行,您将在 $out 上拥有数组。也许你应该考虑使用正则表达式。

$str = '1 hello there 6 foo 37 bar';
$temp = explode(' ', $str);
$out = [];
$key = -1;

foreach ($temp as $word) {
    if (is_numeric($word)) {
        $key = $word;
        $out[$key] = '';
    } else if ($key != -1) {
        $out[$key] .= $word . ' ';
    }
}

使用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);

输出:

Array
(
    [1] => hello there 
    [6] => foo 
    [37] => bar
)

您可以使用正则表达式,live demo

<?php

$string = '1 hello there 6 foo 37 bar';
preg_match_all('/([\d]+)[\s]+([\D]+)/', $string, $matches);
print_r(array_combine($matches[1], $matches[2]));