Search code examples
phppreg-split

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?


Solution

  • 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);