Is there a specific (standardised) way of splitting up a URL path in to path components? I’ve looked at RFC 2396 and can’t see a routine for doing so.
Originally I just used PHP’s explode()
method to break the string into an array when it encounters each /
, but when testing it against Cocoa's NSURL
class, I get two different results:
The test URL: https://example.com/rest/api///v2.1.1/noun/verb////12345/additional/stuff///
NSURL:
["/", "rest", "api", "v2.1.1", "noun", "verb", "12345", "additional", "stuff", "/“]
My PHP method:
Array ( [0] => [1] => rest [2] => api [3] => [4] => [5] => v2.1.1 [6] => noun [7] => verb [8] => [9] => [10] => [11] => 12345 [12] => additional [13] => stuff [14] => [15] => [16] => )
I realise RFC 2396 has been replaced with RFC 3986, but NSURL uses 2396 and that’s what I’m testing against as it’ll be the client side implementation.
I'm not aware of any standard way to do this and to be honest, I'm not that familiar with RFC2396.
However, for your given example, you could use preg_split('#\/+#', $uriPath)
to split by any number of forward slashes and then check if the first and last elements of the resulting array are empty strings - if they are, replace them by a single slash each.