【问题标题】:Turn a long string with numbers to array将带有数字的长字符串转换为数组
【发布时间】:2017-11-14 02:46:11
【问题描述】:

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

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

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

【问题讨论】:

  • 首先,SO想先看看您的方法,以及有关您遇到的特定问题的特定问题。其次,split 将整个内容放在空格上,然后使用 is_numeric() 循环遍历它——这只是众多方法中的一种。
  • 数字是唯一的,还是有重复的?
  • @n3wb 号码是唯一的。 domdom,我在想一些关于 preg_split() 的东西,但我无法让它工作,所以我没有在这里发布。
  • 改为检查explode()
  • 但是,您需要小心:如果您的字符串之一实际上包含一个数字怎么办?我想知道输入字符串最初是如何产生的。

标签: php arrays regex explode preg-split


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    您可以使用正则表达式,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]));
    

    【讨论】:

    • 已经有a very similar answer,也许你想指出你的(即正则表达式)有什么不同(更好?)
    • 您的回答与我的主要有何不同?抄袭?
    • @RomanPerekhrest 在这里我不想和你争论。我发誓在我粘贴代码之前我没有看到你的代码。只有 preg_match_all() 来做正则表达式。抄袭怎么说?
    • @KrisRoofe,即使这不是抄袭 - 你在概念上发布相同的方法迟到了
    • 不仅答案迟了,而且它不能像罗马的模式那样处理空格。对结果执行 var_export() 并看到两个元素有一个尾随空格。
    【解决方案3】:

    这应该可行,您将在 $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 . ' ';
        }
    }
    

    【讨论】:

    • 重要的是要注意正则表达式的使用往往较慢,尽管您的代码较少但性能较低。在这种类型的情况下,我打算使用手动操作字符串,对于更复杂的情况,我使用正则表达式。
    • 之前的解决方案(@RomanPerekhrest)在 0.016 秒内执行。我的解决方案耗时 0.012 秒。
    • 如果使用更大的字符串,情况会变得更糟。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-30
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多