view raw
Tyssen Tyssen - 7 months ago 50
PHP Question

Split a string at & but not &&

I have a URI that contains both

and I need to split it into an array only at the single
delimiter, e.g.

should print out

0 => query1=X
1 => query2=A&&B
2 => query3=Y

I know I can use
but can't figure out the regex. Could someone help?


with preg_match_all (all that isn't an isolated ampersand):

preg_match_all('~[^&]+(?:&&[^&]*)*~', $uri, $result);

with preg_split (check forward and backward with lookarounds):

$result = preg_split('~&(?<!&.)(?!&)~', $uri);

or (force the pattern to fail when there's "&&"):

$result = preg_split('~&(?:&(*SKIP)(*F))?~', $uri);

without regex (translate "&&" to another character and explode):

$result = explode('&', strtr($uri, ['%'=>'%%', '&&'=>'%']));
$result = array_map(function($i) { return strtr($i, ['%%'=>'%', '%'=>'&&']); }, $result);