-1

I need to split my GET string into some array. The string looks like this:

ident[0]=<IDENT_0>&value[0]=<VALUE_0>&version[0]=<VERSION_0>&....&ident[N]=<IDENT_N>&value[N]=<VALUE_N>&version[N]=<VERSION_N>

So, I need to split this string by every third ampersand character, like this:

ident[0]=<IDENT_0>&value[0]=<VALUE_0>&version[0]=<VERSION_0>
ident[1]=<IDENT_1>&value[1]=<VALUE_1>&version[1]=<VERSION_1> and so on...

How can I do it? What regular expression should I use? Or is here some better way to do it?

Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138

2 Answers2

0

You can use preg_split with this pattern: &(?=ident)

$result = preg_split('~&(?=ident)~', $yourstring);

regex detail: &(?=ident) means & followed by ident

(?=..) is a lookahead assertion that performs only a check but match nothing.

Or using preg_match_all:

preg_match_all('~(?<=^|&)[^&]+&[^&]+&[^&]+(?=&|$)~', $yourstring, &matches);
$result = $matches[0];

pattern detail: (?<=..) is a lookbehind assertion

(?<=^|&) means preceded by the begining of the string ^ or an ampersand.
[^&]+ means all characters except the ampersand one or more times.
(?=&|$) means followed by an ampersand or the end of the string $.

Or you can use explode, and then a for loop:

$items = explode('&', $yourstring);
for ( $i=0; $i<sizeof($items); $i += 3 ) {
    $result[] = implode('&', array_slice($items, $i, 3));
} 
Casimir et Hippolyte
  • 88,009
  • 5
  • 94
  • 125
0

There is a better way (assuming this is data being sent to your PHP page, not some other thing you're dealing with).

PHP provides a "magic" array called $_GET which already has the values parsed out for you.

For example:

one=1&two=2&three=3

Would result in this array:

Array ( [one] => 1 [two] => 2 [three] => 3 )

So you could access the variables like so:

$oneValue = $_GET['one'];  // answer is 1
$twoValue = $_GET['two'];  // and so on

If you provide array indexes, which your example does, it'll sort those out for you as well. So, to use your example above $_GET would look like:

Array
(
    [ident] => Array
        (
            [0] => <IDENT_0>
            [N] => <IDENT_N>
        )

    [value] => Array
        (
            [0] => <VALUE_0>
            [N] => <VALUE_N>
        )

    [version] => Array
        (
            [0] => <VERSION_0>
            [N] => <VERSION_N>
        )
)

I'd assume your N keys will actually be numbers, so you'll be able to look them up like so:

$_GET['ident'][0]     // =>   <IDENT_0>
$_GET['value'][0]     // =>   <VALUE_0>
$_GET['version'][0]   // =>   <VERSION_0>

You could loop across them all or whatever, and you will never have to worry about splitting them all out yourself.

Hope it helps you.

Mark Embling
  • 12,605
  • 8
  • 39
  • 53