我在找一個辦法把像1 hello there 6 foo 37 bar
一個字符串數組,如:打開一個長串號碼數組
Array ([1] => "hello there",
[6] => "foo",
[37] => "bar")
每個號碼可獲之後到來的字符串的索引。我想得到如此的幫助。謝謝! :)
我在找一個辦法把像1 hello there 6 foo 37 bar
一個字符串數組,如:打開一個長串號碼數組
Array ([1] => "hello there",
[6] => "foo",
[37] => "bar")
每個號碼可獲之後到來的字符串的索引。我想得到如此的幫助。謝謝! :)
使用preg_match_all
和array_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
)
這應該工作,你將有美元陣列。也許你應該考慮使用正則表達式。
$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 . ' ';
}
}
您可以使用正則表達式,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]));
已經有[非常相似的答案](https://stackoverflow.com/a/44502775/3316645),也許你想指出你的(正則表達式,是)是不同的(更好?) – domsson
以及如何你的答案與我的主要不同嗎?抄襲? – RomanPerekhrest
@RomanPerekhrest在這裏我不想和你爭論。我發誓在粘貼我的代碼之前,我沒有看到您的代碼。只有preg_match_all()才能執行正則表達式。你怎麼說剽竊? –
首先,所以希望首先看到您的方法,以及您遇到的具體問題的具體問題。其次,[split](http://php.net/manual/en/function.explode.php)整個空間上的東西,然後用[is_numeric()](http://php.net/manual /en/function.is-numeric.php) - 只是衆多方法之一。 – domsson
是唯一的數字,還是重複? – n3wb
@ n3wb數字是唯一的。 domdom,我想的是preg_split(),但是我無法使它工作,所以我沒有在這裏發佈它。 –