2013-09-25 140 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