1

I have a problem with this:

<?php $url = 'aa=bb&cc=dd&ee=ff';

For something like this:

<?php $url = array('aa' => 'bb', 'cc' => 'dd', 'ee' => 'ff');

My code:

<?php

$url = 'aa=bb&cc=dd&ee=ff';
preg_match_all('[(\w+)=(\w+)]', $url, $matches);
var_export($matches);

Result:

array ( 0 => array ( 0 => 'aa=bb', 1 => 'cc=dd', 2 => 'ee=ff', ), 1 => array ( 0 => 'aa', 1 => 'cc', 2 => 'ee', ), 2 => array ( 0 => 'bb', 1 => 'dd', 2 => 'ff', ), )

It's almost okay, I just want to get rid of this first key. Thank you for your help.

sopskirk
  • 45
  • 4
  • 1
    The key lesson here is that for common problems like this (breaking apart URL query strings) there is always an existing solution that has already been written, tested and debugged. – Andy Lester Nov 12 '18 at 16:40

2 Answers2

2

The parse_str() function parses a query string into variables.

$url = 'aa=bb&cc=dd&ee=ff';

parse_str($url, $matches);

print_r($matches);
suresh bambhaniya
  • 1,687
  • 1
  • 10
  • 20
2

Actually you can get associative array by many different ways e.g with regex, using explode by & and so on.

But If I were you, I'll use parse_str()

<?php
$url = 'aa=bb&cc=dd&ee=ff';
parse_str($url, $query);
print_r($query);
?>

Output:

Array (
 [aa] => bb 
 [cc] => dd 
 [ee] => ff 
)

DEMO: https://3v4l.org/fjadK

A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103