引爆两个项目列表中的数组作为重点=>价值 [英] explode two-item-list in array as key=>value

查看:127
本文介绍了引爆两个项目列表中的数组作为重点=>价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想爆炸多行字符串像这样

I'd like to explode a multi-line-string like this

color:red
material:metal

像这样的数组

$array['color']=red
$array['material']=metal

任何想法?

推荐答案

使用爆炸(),你可以使用正规的,但它很简单没有足够的开销。

Use explode(), you can use a regexp for it, but it's simple enough without the overhead.

$data = array();
foreach (explode("\n", $dataString) as $cLine) {
    list ($cKey, $cValue) = explode(':', $cLine, 2);
    $data[$cKey] = $cValue;
}

由于在评论中提到的,如果数据是从一个Windows / DOS环境未来很可能有CRLF换行符,添加的foreach之前以下行()将解决

$dataString = str_replace("\r", "", $dataString); // remove possible \r characters

使用正则表达式另一种可以使用 preg_match_all很愉快() array_combine()

The alternative with regexp can be quite pleasant using preg_match_all() and array_combine():

$matches = array();
preg_match_all('/^(.+?):(.+)$/m', $dataString, $matches);
$data = array_combine($matches[1], $matches[2]);

这篇关于引爆两个项目列表中的数组作为重点=>价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆