Reputation: 2528
I have these urls from a web log:
http://www.domain.com/page?s=194&client=151678&m=a4a&v=1&g=54
http://www.domain.com/page?s=51&client=617171&m=b4z&v=8&g=97
How can I convert this URL in an array in PHPso i will have an array like this
array(
'page' => array(
's' => 194,
'client' => 151678
'm' => 'a4a',
'v' => 1,
'g' => 54
)
etc..
)
then later I can loop to that array to find duplicates or validate the information correctly.
Upvotes: 25
Views: 32441
Reputation: 34877
PHP has a native function for that, the parse_str function. You can use it like:
parse_str($_SERVER['QUERY_STRING'], $outputArray);
This will do just what you need.
Upvotes: 35
Reputation: 20150
Use parse_url function like
<?php
$url = 'http://username:password@hostname/path?arg=value#anchor';
print_r(parse_url($url));
echo parse_url($url, PHP_URL_PATH);
?>
Which will give you the following array output
Array
(
[scheme] => http
[host] => hostname
[user] => username
[pass] => password
[path] => /path
[query] => arg=value
[fragment] => anchor
)
And from the query you can easily split it as to (key,value) paira. Hope this helps.:)
Upvotes: 1
Reputation: 145
Assuming from your question that path will always be /page
, the array containing the parsed URLs cannot have multiple page
indexes so you should use numeric indexes.
Try this:
$urls_parsed = array();
foreach ($url_strings as $url_string) {
$url = parse_url($url_string);
$urls_parsed[] = parse_str($url['query']);
}
$url_strings
is an array containing all the URLs you want to parse in string format.
$urls_parsed
is the resulting array containing the URLs parsed in the format you requested.
Upvotes: 1
Reputation: 961
There may be a better way to do this but this is what I came up with.
<?php
$url = 'http://www.domain.com/page?s=194&client=151678&m=a4a&v=1&g=54';
$remove_http = str_replace('http://', '', $url);
$split_url = explode('?', $remove_http);
$get_page_name = explode('/', $split_url[0]);
$page_name = $get_page_name[1];
$split_parameters = explode('&', $split_url[1]);
for($i = 0; $i < count($split_parameters); $i++) {
$final_split = explode('=', $split_parameters[$i]);
$split_complete[$page_name][$final_split[0]] = $final_split[1];
}
var_dump($split_complete);
?>
Upvotes: 28
Reputation: 3564
With parse_url()
you can parse the URL to an associative array. In the result array you get amongst others the query part. Then you can use parse_str()
for parsing the query part to your new array.
Upvotes: 6
Reputation: 76910
You could do:
function convertUrlToArray($url){
$url = str_replace("http://www.domain.com/page?", "", $url);
$urlExploded = explode("&", $url);
$return = array();
foreach ($urlExploded as $param){
$explodedPar = explode("=", $param);
$return[$explodedPar[0]] = $explodedPar[1];
}
return $return;
}
$url1 = convertUrlToArray("http://www.domain.com/page?s=51&client=617171&m=b4z&v=8&g=97");
var_dump($url1);
example here http://codepad.org/KIDKPzaU
Upvotes: 0