if the format of the string is set in stone, you could do something like:
$string = "var1=val1 var2=val2 var3='this is a test'";
$vars = array();
$i = 0;
while ($i < strlen($string)) {
$eqIndex = strpos($string, "=", $i);
$varName = substr($string, $i, $eqIndex - $i);
$i = $eqIndex + 1;
if ($string[$i] == "'")
{
$varEndIndex = strpos($string, "'", ++$i);
}
else
{
$varEndIndex = strpos($string, " ", $i);
if ($varEndIndex === FALSE) $varEndIndex = strlen($string);
}
$varValue = substr($string, $i, $varEndIndex - $i);
$vars[$varName] = $varValue;
$i = $varEndIndex + 1;
}
print_r($vars);
EDIT:
More robust function that handles escaped chars in the quoted values:
function getVarNameEnd($string, $offset) {
$len = strlen($string);
$i = $offset;
while ($i < $len) {
if ($string[$i] == "=")
return $i;
$i++;
}
return $len;
}
function getValueEnd($string, $offset) {
$len = strlen($string);
$i = $offset;
if ($string[$i] == "'") {
$quotedValue = true;
$i++;
}
while ($i < $len) {
if ($string[$i] == "\\" && $quotedValue)
$i++;
else if ($string[$i] == "'" && $quotedValue)
return $i + 1;
else if ($string[$i] == " " && !$quotedValue)
return $i;
$i++;
}
return $len;
}
function getVars($string) {
$i = 0;
$len = strlen($string);
$vars = array();
while ($i < $len) {
$varEndIndex = getVarNameEnd($string, $i);
$name = substr($string, $i, $varEndIndex - $i);
$i = $varEndIndex + 1;
$valEndIndex = getValueEnd($string, $i);
$value = substr($string, $i, $valEndIndex - $i);
$i = $valEndIndex + 1;
$vars[$name] = $value;
}
return $vars;
}
$v = getVars("var1=var1 var2='this is a test' var3='this has an escaped \' in it' var4=lastval");
print_r($v);