PHP分割分隔字符串成键/值对(关联数组) [英] PHP Split Delimited String into Key/Value Pairs (Associative Array)

查看:272
本文介绍了PHP分割分隔字符串成键/值对(关联数组)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的字符串:

I have a string like this:

key1\value1\key2\value2\key3\value3\key4\value4\key5\value5

和我想它是一个关联数组,这样我可以做的:

And I'd like it to be an associative array so that I can do:

echo $myArray['key1']; // prints value1
echo $myArray['key3']; // prints value3
//etc...

我知道我可以在反斜线爆炸,但不知道如何从那里。

I know I can explode on the backslash, but not sure how to go from there.

推荐答案

通过的正则表达式 = http://php.net/$p$pg_match_all相对=nofollow> preg_match_all 和的 array_combine 往往是最短,最快的选项:

Using a simple regex via preg_match_all and array_combine is often the shortest and quickest option:

 preg_match_all("/([^\\\\]+)\\\\([^\\\\]+)/", $string, $p);
 $array = array_combine($p[1], $p[2]);

现在,这是当然的特例。无论的和的的是由<大骨节病> \\ 反斜线隔开,都是对他们来说。正则表达式也因必要的双重转义更长一点。

Now this is of course a special case. Both keys and values are separated by a \ backslash, as are all pairs of them. The regex is also a bit lengthier due to the necessary double escaping.

不过这个方案可以推广到其他键:值,风格的字符串

However this scheme can be generalized to other key:value,-style strings.

常见的变化包括 和<大骨节病> = 以键/值分隔符和<大骨节病>,或<大骨节病>&安培; 及其他作为对分隔符。正则表达式变成在这种情况下相当明显(与 / X 的可读性标志):

Common variations include : and = as key/value separators, and , or & and others as pair delimiters. The regex becomes rather obvious in such cases (with the /x flag for readability):

 #                    ↓    ↓    ↓
 preg_match_all("/ ([^:]+) : ([^,]+) /x", $string, $p);
 $array = array_combine($p[1], $p[2]);

这使得它超级简单交换其他分隔符。


  • 的等号 = ,而不是冒号

  • 例如 \\\\牛逼作为分隔符对(制表符分隔键:值列表)

  • 经典&安培; ; 作为key = value对之间的分隔符

  • 或只是 \\\\小号空格或 \\\\ñ换行符偶数。

  • Equal signs = instead of : colons.
  • For example \\t as pair delimiter (tab-separated key:value lists)
  • Classic & or ; as separator between key=value pairs.
  • Or just \\s spaces or \\n newlines even.

您可以使它更灵活/宽容,允许键/值/对之间不同的分隔符:

You can make it more flexible/forgiving by allowing different delimiters between keys/values/pairs:

 #                    ↓      ↓       ↓
 preg_match_all("/ ([^:=]+) [:=]+ ([^,+&]+) /x", $string, $p);

如果双方键=值,键2:VALUE2 ++ KEY3 == VALUE3 会工作。这可以使更多的人friendlinies感(又名非技术用户)。

Where both key=value,key2:value2++key3==value3 would work. Which can make sense for more human-friendlinies (AKA non-technical users).

通常情况下,你可能想禁止任何东西,但经典的标识符。只需要使用 \\ w + 字串模式,使正则表达式跳过不必要的OCCURENCES:

Oftentimes you may want to prohibit anything but classic key identifiers. Just use a \w+ word string pattern to make the regex skip over unwanted occurences:

 #                   ↓   ↓    ↓
 preg_match_all("/ (\w+) = ([^,]+) /x", $string, $p);

这是最简单的白名单的做法。如果OTOH你想的断言的/制约整个键/值的字符串事前,然后制定一个单独的 preg_match(/ ^(\\ w + = [^,] + (,| $))+ /,...

This is the most trivial whitelisting approach. If OTOH you want to assert/constrain the whole key/value string beforehand, then craft a separate preg_match("/^(\w+=[^,]+(,|$))+/", …

您可以跳过一些后处理步骤(如 修剪 与加入少量的键和值):

You can skip a few post-processing steps (such as trim on keys and values) with a small addition:

 preg_match_all("/ \s*([^=]+) \s*=\s* ([^,]+) (?<!\s) /x", $string, $p);

或者例如可选报价:

Or for instance optional quotes:

 preg_match_all("/ \s*([^=]+) \s*=\s* '? ([^,]+) (?<![\s']) /x", $string, $p);

INI式萃取

你可以制作一个基线INI文件提取方法:

INI-style extraction

And you can craft a baseline INI-file extraction method:

 preg_match_all("/^ \s*(\w+) \s*=\s* ['\"]?(.+?)['\"]? \s* $/xm", $string, $p);

请注意,这仅仅是一个的原油集的共同INI方案。

Please note that this is just a crude subset of common INI schemes.

如果你有一个键=值和放大器;键2 =值字符串已经,那么的 parse_str 就像一个魅力。但是,它与 strtr函数的效率组合甚至可以变化的过程分隔符等

If you have a key=value&key2=value2 string already, then parse_str works like a charm. But by combining it with strtr can even process varying other delimiters:

 #                         ↓↓    ↑↑
 parse_str(strtr($string, ":,", "=&"), $pairs);

其中有一对夫妇的的优点和自己的缺点的


  • 甚至超过了两行正则表达式的方法更短。

  • predefines一个众所周知的转义机制,如%2F 特殊字符)。

  • 不容许内变化的分隔符,或转义符。

  • 自动转换键[] = 来阵列,您可能会或可能不希望虽然。

  • Even shorter than the two-line regex approach.
  • Predefines a well-known escaping mechanism, such as %2F for special characters).
  • Does not permit varying delimiters, or unescaped delimiters within.
  • Automatically converts keys[]= to arrays, which you may or may not want though.

您会发现手动键/值字符串扩展的例子很多。虽然这是通常更code。 爆炸是PHP有点过滥,由于优化的假设。分析结果往往后要慢但由于人工的foreach 和数组集合。

You'll find many examples of manual key/value string expansion. Though this is often more code. explode is somewhat overused in PHP due to optimization assumptions. After profiling often turns out to be slower however due to the manual foreach and array collection.

这篇关于PHP分割分隔字符串成键/值对(关联数组)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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