Tyssen
Tyssen

Reputation: 1711

Split a string at & but not &&

I have a URI that contains both & and && and I need to split it into an array only at the single & delimiter, e.g. query1=X&query2=A&&B&query3=Y

should print out

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

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

Upvotes: 3

Views: 492

Answers (2)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89567

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('~(?<!&)(?:&&)*+\K&(?!&)~', $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);

Upvotes: 5

chiliNUT
chiliNUT

Reputation: 19573

Another preg split:

preg_split("/(?<!&)&(?!&)/",$uri)

(Grab an ampersand not followed by or preceded by an ampersand)

Upvotes: 1

Related Questions