I have this string in PHP:
$string = "name=Shake & Bake&difficulty=easy";
For which I want to parse into array:
Array
(
[name] => Shake & Bake
[difficulty] => easy
)
NOT:
Array
(
[name] => Shake
[difficulty] => easy
)
What is the most efficient way to do this ?
There's probably a more effective way of doing this, but try
$foo = 'name=Shake & Bake&difficulty=easy';
$pairs = preg_split('{&(?=[^\s])}',$foo);
//$pairs = preg_split('/&(?=[^\s])/',$foo); //equivalent, using different delimiters.
//$pairs = preg_split('%&(?=[^\s])%',$foo); //equivalent, using different delimiters.
$done = Array();
foreach($pairs as $keyvalue){
$parts = preg_split('{=}',$keyvalue);
$done[$parts[0]] = $parts[1];
}
print_r($done);
PHP's regex engine is PCRE, and it supports look ahead assertions. Googling around for PCRE, PHP, RegEx, look ahead assertions and zero width assertions should give you more than you ever want to know on the subject.