2017-06-12 42 views
1

我在找一個辦法把像1 hello there 6 foo 37 bar一個字符串數組,如:打開一個長串號碼數組

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

每個號碼可獲之後到來的字符串的索引。我想得到如此的幫助。謝謝! :)

+2

首先,所以希望首先看到您的方法,以及您遇到的具體問題的具體問題。其次,[split](http://php.net/manual/en/function.explode.php)整個空間上的東西,然後用[is_numeric()](http://php.net/manual /en/function.is-numeric.php) - 只是衆多方法之一。 – domsson

+0

是唯一的數字,還是重複? – n3wb

+0

@ n3wb數字是唯一的。 domdom,我想的是preg_split(),但是我無法使它工作,所以我沒有在這裏發佈它。 –

回答

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

輸出:

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

這應該工作,你將有美元陣列。也許你應該考慮使用正則表達式。

$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 . ' '; 
    } 
} 
+0

重要的是要注意,正則表達式的使用往往比較慢,儘管代碼少但性能低。在這種情況下,我打算使用手動操作字符串,我使用正則表達式來處理更復雜的情況。 – OmaRPR

+0

以前的解決方案(由@RomanPerekhrest)在0.016秒執行。我的解決方案花了0.012秒。 – OmaRPR

+0

這是一個很棒的觀點。我一定會考慮的。 –

0

您可以使用正則表達式,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])); 
+0

已經有[非常相似的答案](https://stackoverflow.com/a/44502775/3316645),也許你想指出你的(正則表達式,是)是不同的(更好?) – domsson

+0

以及如何你的答案與我的主要不同嗎?抄襲? – RomanPerekhrest

+1

@RomanPerekhrest在這裏我不想和你爭論。我發誓在粘貼我的代碼之前,我沒有看到您的代碼。只有preg_match_all()才能執行正則表達式。你怎麼說剽竊? –

相關問題