从字符串中提取参数的最佳方式


Best way to extract params from string

我有一个name="value"类型的字符串,看起来像。。。

{user type="active" name="james green" id="45" group="active users"}

我需要一个通用函数来解析这种类型的字符串,从这种格式中提取所有的名称/值对作为数组(总是在双引号内,每个参数由一个空格分隔,用{}括起来(,以及初始的开头词(在这种情况下是user(。

任何想法都将不胜感激。

基本上是

 preg_match_all('~('w+)="(.+?)"~', $string, $matches, PREG_SET_ORDER);
 foreach($matches as $m)
     $array[$m[1]] = $m[2]
$string = '{user type="active" name="james green" id="45" group="active users"}';
$user = simplexml_load_string('<' . substr($string, 1, -1) .'/>');
print_r(current($user));

将给出

Array
(
    [type] => active
    [name] => james green
    [id] => 45
    [group] => active users
)

但这应该很容易,更适合用Regex来解决。

name"james green"可以像这样提取

<?php
    $point=strpos( $string, 'name="' ) + strlen('name="');
    $string = substr($string,$point);
    $point=strpos( $string, '"' );
    $string = substr($string,$point);
    echo $string; // james green
?>
$string = '{user type="active" name="james green" id="45" group="active users"}';
$string = str_replace('{', '', $string); // delete brackets
$array = explode(' ', $string);
$var = array_shift($array); // <-- here is 'user'
foreach($array as $pair)
{
$arr = explode('=', $pair);
$arr[0]; // <-- here is the key
$arr[1]; // <-- here is the value
}

未测试!