# Parsing URL segments

The .htaccess file redirects all requests to this file and the $_REQUEST['path'] variable contains the url after the base url. $url = '';
$urlSegments = [];$resource = '';
$action = '';$parameters = [];

if(isset($_REQUEST['path'])){$url = $_REQUEST['path'];$urlSegments = explode('/', $url); if(!empty($urlSegments[0])){
$resource =$urlSegments[0];
array_shift($urlSegments); if(!empty($urlSegments[0])){
$action =$urlSegments[0];
array_shift($urlSegments);$parameters = $urlSegments; } } }$method = $_SERVER['REQUEST_METHOD'];  I was wondering if there is an better way (with regex maybe?) to parse the url, loop through it and extract the MVC data from the url. array_shift looks ugly and it feels that there must be a better way. ## 2 Answers This example: $uri   = '/users/create';
$regex = '~^/(?P<resource>.*?)/(?P<action>.*?)/?$~';

if (preg_match($regex,$uri, $matches)) { print_r($matches);
}


Will produce following result:

Array
(
[0] => /users/create
[resource] => users
[1] => users
[action] => create
[2] => create
)


Hope this helps.

• If that array could some how be cleaned up so it only had the associative keys in it, then you could use extract to get those variables out of it. However, what does this do in the instance that there are some parameters as well? I'm horrible with regex, so just curious... – mseancole Jun 12 '12 at 17:37
• When match attempt is successful, everything is stored inside resulting array(i.e. $matches). Which includes a) full match; b) named group in first parens; c) just group without name(i.e. resource); d) second named group; and e) same group without name. – ioseb Jun 12 '12 at 17:42 Disclaimer: I do eventually answer your question, there are just some other things I wished to point out. GET vs REQUEST First of all, I would consider using $_GET instead of $_REQUEST. I'm assuming its get your using judging by the data you are passing. It is generally a better idea to use the specific array you need if you know it rather than one that could potentially contain data from another source. For example, should you ever create a form with a path input, it will supersede any get path. But this isn't even necessary, the remote user can change that value should they wish. However, if you were to call them separately $_GET[ 'path' ] and $_POST[ 'path' ] you will be able to use them both together without losing any information and they are less likely to be hijacked (minus get, its pretty easy to hijack that). Filter Input Take a look at PHP's filter_input(). It will mean you only have to type that $url variable once and has the added benefit of sanitizing your input.

$url = filter_input( INPUT_GET, 'path', FILTER_SANITIZE_STRING ); //returns false if not set so if($url ) {
//etc...
}


Array Shift

PHP's array_shift() returns the value shifted, so there is no reason to specifically call that value, simply set the variable as you shift it.

$resource = array_shift($urlSegments );


Order of Logic

Instead of checking if the value of $urlSegments is empty, I would set it first then check it. A couple of reasons for this. What if "path" starts with a forward slash "/"? I believe explode will produce an empty element at the very beginning. Unless this is the desired result, it could cause errors. Also, it removes the need for those magic numbers, i.e.($urlSegments[0]) Yes its obvious where it came from and why you are using it, but it is a bad habit and is not extendable.

$resource = array_shift($urlSegments );
if( ! empty( $urlSegments ) ) { if( ! empty($resource ) ) {
$action = array_shift($urlSegments );
if( ! empty( $action ) ) {$parameters = $urlSegments; } } else { //handle$url starting with a forward slash
//this is where having this set up in functions would help
}
}


Here's the Better Solution: Only one parameter

However, the cleanest way of all is to guarantee the length of $urlSegments, then use PHP's list(). So, you can use array_pad() to fill out the rest of $urlSegments should it be too short, otherwise list() will produce errors. If it is already of the proper size it will not do anything so you don't need to test it first. Now, to ensure that it doesn't already contain empty elements, that it didn't start with a forward slash, or have any double slashes, you should run it through array_filter(). Note: This will remove any element that could be considered "false" (0, '', null, -1, etc) so be careful here. This also means that if you were using empty or false parameters before, then it may not work the same way. Edit: This is if you use array_filter() without a callback, you could always make your own callback function to ignore certain values.

$urlSegments = array_filter($urlSegments );
$urlSegments = array_pad($urlSegments, 3, '' );
list( $resource,$action, $parameters ) =$urlSegments;


Here's the Better Solution: Multiple parameters

I just realized that $urlSegments could very likely be longer than 3 elements. In this case, I would filter and pad it like I did above, shift the first two elements into their respective variables then set $parameters to whatever remains of $urlSegments. Padding it first ensures that each variable has a default value of an empty string. $urlSegments = array_filter( $urlSegments );$urlSegments = array_pad( $urlSegments, 3, '' );$resource = array_shift( $urlSegments );//default = '';$action = array_shift( $urlSegments );//default = '';$parameters = $urlSegments;//default = array( '' );  Shorthand Finally, it is rarely a good idea to use shorthand in PHP. If I did not know what you were trying to accomplish, or had a slightly older version of PHP, I would think that $urlSegments = []; was syntactically wrong. Yes it works, but you could run across problems in the future. Not to mention its just easier to read \$urlSegments = array();

Regex

That should clean up your code considerably. I would hesitate to suggest any regex, mainly because I find it extremely difficult to read.

Edits

Edited a few times to clean up post and add the second "Better Solution".

• @msanford: It's always good when you walk away from teaching someone something having learned something yourself. A lot of that explanation is me walking myself through it :) – mseancole Jun 12 '12 at 19:01
• @showerhead I really appreciate all the effort, but it was a little bit of an over kill, you tell me about santization, but that is not really needed at this point, since we'r just parsing the URL, we are not posting to the database. Also about the shorthand thing, [] instead of array(), go read php 5.4 release log ;) – onlineracoon Jun 13 '12 at 11:04
• @onlineracoon I have read the 5.4 release log, at least enough to know about that method. As I said, I know what you are trying to do. But shorthand is not always the best way if you want to have readable code. Not only that but, not everyone is going to know about it, or be able to support it should you ever need to move it to another server. Sanitizing is still important, especially with URL parsing because of PHP injection. I don't know exactly how they do it, think it has more to do with eval users, but its always better to ensure it isn't possible. Especially if its only one extra line. – mseancole Jun 13 '12 at 11:57