Best way to extract params from string
I have a name="value"
type string that looks like...
{user type="active" name="james green" id="45" group="active users"}
I need a generic function that will parse this type of string extracting all of the name/value pairs as an array from this format (always within double quot开发者_开发问答es and each param sepertated by a space, enclosed in {}
) as well as the initial opening word (user
in this case).
Any ideas would be much appreciated.
basically
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));
will give
Array
(
[type] => active
[name] => james green
[id] => 45
[group] => active users
)
But that should be easy and more appropriate to solve with a Regex.
name "james green" can be extracted like this
<?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
}
Not tested!
精彩评论