What is the best way to parse a URL into its corresponding paths, such that
https://www.example.com/path/to/directory/file.jpeg?param1=foo¶m2=bar
Results in an array holding
Array(
["scheme"] => "https",
["host"] => www.example.com
["directory"] => "path/to/directory"
["filename"] => "file"
["extension] => "jpeg"
["path"] => "path/to/directory/file.jpeg",
["file"] => "file.jpeg"
["params"] => Array(
["param1"] => "foo",
["param2"] => "bar"
)
)
Note: The keys do not need to be named like this, they are just an example.
I have looked into parse_url, but it doesn't split up the path fine grained enough, so further manual processing seems inevitable.
Sidenote: I have looked into very many multiple questions and answers, but I can't find any definite reference, thus my question.
The best way is to combine the efforts of multiple builtin php functions such as parse_url (for the basic url parts), parse_str (for the query parameters) and pathinfo (for the directory, filename and extension parts).
parse_url
parse_url will parse the url and split it up into an associative array containing the following keys (if they are present in the url):
parse_str
parse_str can be used to parse the
query
part from parse_url into a multidimensional (if needed) associative array.pathinfo
pathinfo can be used to parse the
path
part from parse_url into an associative array which can contain the following keys:Putting it all together
Giving it a test
will yield these corresponding results: