South Africa’s biggest forum. Discuss, discover, and connect with thousands of members.
<?php
$str="firstname=Hello;world;surname=World;address=My Address; Here; etc etc";
$field = "";
$list=array();
foreach (explode(";", $str) as $x) {
// do we have a valid field seperator?
if(strpos($x, "=")===False) // no
$field .= ';'.$x;
else
$field = $x; // yes
$tmp = explode("=", $field);
$list[$tmp[0]]=$tmp[1];
}
print_r($list);
Oh and the output is:
LOCAL: chrisb@rhino [ 16:04:58 ][ ~ ]
> ./play.php
Array
(
[firstname] => Hello;world
[surname] => World
[address] => My Address; Here; etc etc
)
$line = 'id=1;firstname=First Name;surname=Surname;Address=Try;To;Break;Me';
$results = array();
$segments = explode(';', $line);
$last_key = '';
foreach ($segments as $segment)
{
if (preg_match('/^([a-z0-9]+)=(.*)$/i', $segment, $matches))
{
$last_key = $matches[1];
$results[$last_key] = $matches[2];
}
else
{
$results[$last_key] .= ';' . $segment;
}
}
... may as well have linked me to google
thanks cbrunsdonza
I originally tried parsing it character by character, but it was too painful a solution
I tried a regex split, something like (([a-z0-9]+)=(.*?)+ but I'm evidently not too clued up on regexes
and I was battling with the greedy ;
I landed up using this; not sure how efficient it is but it works.
Code:$line = 'id=1;firstname=First Name;surname=Surname;Address=Try;To;Break;Me'; $results = array(); $segments = explode(';', $line); $last_key = ''; foreach ($segments as $segment) { if (preg_match('/^([a-z0-9]+)=(.*)$/i', $segment, $matches)) { $last_key = $matches[1]; $results[$last_key] = $matches[2]; } else { $results[$last_key] .= ';' . $segment; } }
I would:
1 - Build a list of all keys.
2 - Find all keys and split on key.
3 - Solve for key value after the =.
4 - Strip trailing ;
Keys are:
firstname=
surname=
address=
...
Add error handler for keys appearing more than once.
Other approaches would lead to problems when values contain "=" or ";".
If you wanted to do it without regex you could just as easily use substr to do it. My personal philosophy is if you can do it without regex, do it. Use regex as a last resort, not a first.
$string = 'var;1=value1;2;var2=value2;var3=value;3;';
preg_match_all('/([^;][^=]+)=([^=]+)(?=;)/', $string, $matches);
$result = array_combine($matches[1], $matches[2]);
Just remember that CPU cycles are cheap so rather write a few extra lines of code if you it makes more sense. We no longer need to code like we did back in the 80's where we spent 99% of our time optimising a single line.