如何使用其中一个preg_函数将复杂的字符串解析为数组?

时间:2014-12-24 00:13:44

标签: php parsing

我有这样的事情:

[
    "username=required:true|min:2|max:14",
    "email=required:true|email:true",
    "password=required:true|min:6|max:22",
    "passwordRepeat=required:true|match:password"
]

我想要

[
    "username" => [
        "required"  => true,
        "min"       => 2,
        "max"       => 14,
    ],
    "email" => [
        "required"  => true,
        "email"     => true,
    ],
    "password" => [
        "required"  => true,
        "min"       => 6,
        "max"       => 22,
    ],
    "passwordRepeat" => [
        "required"  => true,
        "match"     => "password"
    ]
]

我尝试了很多使用preg_ *函数,但我仍然没有设法得到正确的模式。有人可以帮我弄这个吗?感谢任何帮助,谢谢!

1 个答案:

答案 0 :(得分:2)

为什么在可以反复explode()时使用正则表达式?

每个人都喜欢爆炸。让我们这样做。


引爆:<!/ H3>
$parts = [
    "username=required:true|min:2|max:14",
    "email=required:true|email:true",
    "password=required:true|min:6|max:22",
    "passwordRepeat=required:true|match:password"
];

$result = [];
foreach ($parts as $part) {
    list($property, $attributes) = explode('=', $part, 2);
    foreach (explode("|", $attributes) as $attribute) {
        list($name, $value) = explode(":", $attribute, 2);
        $result[$property][$name] = $value;
    }
}

var_export($result);

臂架:<!/ H3>
array (
  'username' => 
  array (
    'required' => 'true',
    'min' => '2',
    'max' => '14',
  ),
  'email' => 
  array (
    'required' => 'true',
    'email' => 'true',
  ),
  'password' => 
  array (
    'required' => 'true',
    'min' => '6',
    'max' => '22',
  ),
  'passwordRepeat' => 
  array (
    'required' => 'true',
    'match' => 'password',
  ),
)