将字符串拆分为数组并将定界符设置为键 [英] Split a string into an array and set the delimiter as the key
本文介绍了将字符串拆分为数组并将定界符设置为键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这样的数据字符串。
I have a string of data as such.
$str = "abc/text text def/long amount of text ghi/some text"
我有一组定界符
$arr = array('abc/', 'def/', 'ghi/', 'jkl/');
我该怎么做才能获得此输出?
What can I do to get this output?
Array
(
[abc/] => text text
[def/] => long amount of text
[ghi/] => some text
)
还要注意$ arr可能并不总是出现在$ str中。在使用下面@rohitcopyright中的代码后,我只是注意到这是一个问题。
Also note that all the values in $arr may not always appear in $str. I just noticed this to be a problem after using the code from @rohitcopyright below.
推荐答案
您可以使用 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"
}
更新:(删除空项目并重新索引)
Update: (remove empty item and re-index)
$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"
}
更新:(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
)
更新:(9月26日,2013)
您也可以尝试这样做(仅更改以下行才能获得您在评论中提到的结果)
You may try this as well (only change following line to achieve the result that you mentioned in comment)
$array = preg_split( "/([a-zA-Z]{1,4}\/)/", $str, null, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
这篇关于将字符串拆分为数组并将定界符设置为键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文