I have this url: "http://example.com/search/dep_city:LON/arr_city=NYC". How can i get the values "LON" and "NYC" from this url in PHP? This would be easy if url would be in format "dep_city=LON" by using "$_GET['dep_city']" but in this case i am confused how to do this. Thanks in advance for your time and help.
Asked
Active
Viewed 237 times
0
-
Is your application routed? Will everything go to 1 script independent of the URL? Because normal apache will try and find a directory called dep_city:LON without some proper framework or endpoint. – Rentabear Oct 01 '19 at 14:08
-
1Thanks for your comment. Yes, everything will go to 1 script. – octav Oct 01 '19 at 14:28
-
I'd use a combination of regex and $_SERVER[REQUEST_URI]. Working on an example. – Rentabear Oct 01 '19 at 14:30
-
1Thanks in advance for your time. I would very much appreciate a full code snippet, if possible. – octav Oct 01 '19 at 14:42
-
Just added it. ^^ – Rentabear Oct 01 '19 at 14:43
1 Answers
0
Get the URL from the server, explode it into parts. Check the index of : or = for each part, parse it into an array.
<?php
$url = substr( $_SERVER["REQUEST_URI"], 1, strlen($_SERVER["REQUEST_URI"]));
$vars = explode("/", $url);
foreach($vars as $var){
$indexEquals = strpos($var, "=");
if($indexEquals === false){
$indexColon = strpos($var, ":");
$part1 = substr($var, 0, $indexColon);
$part2 = substr($var, $indexColon+1, strlen($var));
}else{
$part1 = substr($var, 0, $indexEquals);
$part2 = substr($var, $indexEquals+1, strlen($var));
}
$params[$part1] = $part2;
}
echo json_encode($params);
die();

Rentabear
- 300
- 2
- 11
-
Yes it gives the array. And after that i use json_decode to get the values (i hope i am doing right like this). Thanks for such prompt reply and for your time! – octav Oct 01 '19 at 15:11
-
Sorry i left this alone for so long. But you don't have to use json_decode. You just don't have to encode it. That was just added to be able to print it for testing. – Rentabear Oct 07 '19 at 10:23