Suppose I have the URL look like: http://www.example.com/category/product/htc/desire, I used $_SERVER['REQUEST_URI'] to get /category/product/htc/desire, how can I convert this "/category/product/htc/desire" to array like:
array
(
[0] => category
[1] => product
....
)
Thanks
asked Mar 19, 2011 at 1:40
Charles Yeung
38.9k33 gold badges94 silver badges133 bronze badges
4 Answers 4
$array = explode('/', trim($_SERVER['REQUEST_URI'], '/'));
answered Mar 19, 2011 at 1:42
Alec Gorge
17.5k10 gold badges63 silver badges71 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Alec Gorge
This method also has the benefit of removing trailing and preceding slashes.
<?php
$url = "/category/product/htc/desire";
$pieces = explode("/", substr($url,1));
print_r($pieces);
?>
obviously $url would be the $_SERVER['REQUEST_URI']
output, see here: http://codepad.org/lIRZNTBI
answered Mar 19, 2011 at 1:43
Mike Lewis
64.4k20 gold badges144 silver badges111 bronze badges
Comments
Have a look at PHP strtok function You can do something like that :
$string = "/category/product/htc/desire";
$arr = aray();
$tok = strtok($string, "/");
while ($tok !== false) {
arr[]= $tok:
$tok = strtok(" \n\t");
}
answered Mar 19, 2011 at 1:46
ArtoAle
2,9872 gold badges27 silver badges50 bronze badges
1 Comment
ArtoAle
actually, explode would be a better solution =)
lang-php