2013-09-25 78 views
3

我有一個數據字符串。將字符串拆分爲數組並將分隔符設置爲鍵

$str = "abc/text text def/long amount of text ghi/some text" 

我有我的分隔符

$arr = array('abc/', 'def/', 'ghi/', 'jkl/'); 

我能做些什麼來得到這個輸出數組?

Array 
(
    [abc/] => text text 
    [def/] => long amount of text 
    [ghi/] => some text 
) 

另請注意,$ arr中的所有值可能不總是出現在$ str中。我剛剛在使用下面的@rohitcopyright代碼後發現這是一個問題。

+0

你能給我們一個確切的輸入例子嗎? –

+0

你的價值觀在哪裏? – SamT

回答

3

您可以使用preg_split代替

$text = "abc/text text def/long amount of text ghi/some text"; 
$output = preg_split("/(abc\/|def\/|ghi)/", $text); 
var_dump($output); 

輸出:

array(4) { 
    [0]=> 
    string(0) "" 
    [1]=> 
    string(10) "text text " 
    [2]=> 
    string(20) "long amount of text " 
    [3]=> 
    string(10) "/some text" 
} 

更新:(刪除空項目,並重新索引)

$output = array_values(array_filter(preg_split("/(abc\/|def\/|ghi)/", $text))); 
var_dump($output); 

輸出:

array(3) { 
    [0]=> 
    string(10) "text text " 
    [1]=> 
    string(20) "long amount of text " 
    [2]=> 
    string(10) "/some text" 
} 

DEMO.

更新:(2013年9月26日)

$str = "abc/text text def/long amount of text ghi/some text"; 
$array = preg_split("/([a-z]{3}\/)/", $str, null, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE); 
$odd = $even = array(); 
foreach($array as $k => $v) 
{ 
    if ($k % 2 == 0) $odd[] = $v; 
    else $even[] = $v; 
} 
$output = array_combine($odd, $even); 

print_r($output); 

輸出:

Array (
    [abc/] => text text 
    [def/] => long amount of text 
    [ghi/] => some text 
) 

DEMO.

更新:(2013年9月26日)

你可以試試這個問題,以及(只更改以下行來實現您在評論中提及的結果)

$array = preg_split("/([a-zA-Z]{1,4}\/)/", $str, null, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE); 

DEMO.

+0

不是我正在尋找。我想讓abc /,def /和ghi /最終成爲我的索引(關鍵字),並且沒有[0],[1]等...... – davipilot

+0

@davipilot,檢查更新。 –

+0

@davipilot,之前我不清楚,對不起,希望你想要這個(最新更新)。 –

0
Try this you will get the exact output as you want. 


$con='abc/text text def/long amount of text ghi/some text'; 
$newCon = explode('/', $con); 
array_shift($newCon); 
$arr = array('abc/', 'def/', 'ghi/'); 
foreach($newCon as $key=>$val){ 
     $newArrStr = str_replace("/", "", $arr[$key+1]); 
     $newVal = str_replace($newArrStr, "", $newCon[$key]); 
    $newArray[$arr[$key]] = $newVal; 
} 
print_r($newArray); 
+0

這是我測試的最接近的答案。我得到以下輸出。 '數組([0] => abc/[1] => def/[2] => ghi/[abc /] =>文本文本[def /] =>長文本量[ghi /] =>一些文本)'我能做些什麼只有以下回報:'數組([abc /] =>文本文本[def /] =>長文本數[ghi /] =>一些文本)' – davipilot

+0

如果添加另一個值到$ arr - 數組,例如jkl /,它沒有出現在$ con字符串中,我注意到這會讓事情變得糟糕。我能做些什麼? – davipilot

+0

它正在完美工作......當然,你在你的代碼中缺少一些東西......只需複製這段代碼並運行它即可。你將得到確切的輸出結果。 – rohitcopyright