dream.scape wrote:You could even use the good ole fashion C style for() loop
Yeah, but the poster specifically wanted to avoid exploding. (Don't we all? 😉) On the other hand, the whole of the rest of this post is predicated on the assumption that the original poster really has determined that explode() is unsuitable for some reason.
NogDog wrote:My first thought was to use strtok() with '.' as the token, but I couldn't figure out how to get around the instance of an empty value ('..').
Um, yeah; that changed in 4.1, didn't it (I botched the code anyway, by reinitialising the string every time: variantvariantvariantvariant.....).
Unless"MUCH larger" means "on the order of several megabytes" I'd go with your code (though I still wonder how much more memory would be required for a $data=explode("\x00", $data)). If that is the size of the data, then I'd parse it while I'm reading it ([man]stream_get_line[/man]) instead of leaving that until after. (And if this code is statically declared in the code, then it would be much better written as an associative array to begin with!)
Actually, I could use stream_get_line on a variable.... lessee... I'm too lazy to write the stream wrapper myself so I'll just whack in the VariableStream class that appears on the [man]stream_wrapper_register[/man] page:
stream_wrapper_register("var", "VariableStream")
or die("Failed to register protocol");
$dataArray = array();
$fp = fopen("var://data", "r");
while(!feof($fp))
{
$name = stream_get_line($fp, 128, "\x00");
$value = stream_get_line($fp, 128, "\x00");
$dataArray[$name]=$value;
}
print_r($dataArray);
Um, yeah, that works. But if this is coming from a file then using stream_get_line() directly on the file handle makes far more sense.
And after all that, if this data doesn't change, use var_dump to make a PHP-parseable file that contains the associative array.
Oh, one last little giggle. Does anyone else feel like having a little ... giggle?
$data.="\x00";
$dataArray = array();
preg_replace('/([a-z0-9]+)\x00([a-z0-9]+)\x00/ei', '$dataArray["$1"]="$2";', $data);
print_r($dataArray);