1

I am trying to take the base URL from a site and be able to print the first and possibly second directory in the path. The code I have tested below works for anything with more than 2 directories (eg. dir/dir/title). The problem is when there is only 1 or two directories in the path (eg dir/title or just title).

<?php
$path = "dir/dir/dir/title";
$posl = substr($path, 0, strpos($path, "/"));
$post_strip = $posl."/";
$new_path = str_replace($post_strip, "", $path);
$new_path = substr($new_path, 0, strpos($new_path, "/"));
echo $new_path;
?>

I was also thinking there might be some way to split the path string at the slashes and hold each of these as an array. Therefore I can just print the specific value of the array as it corresponds to its place in the path.

Any help is greatly appreciated.

1
  • explode() on / is what you want Commented Feb 3, 2012 at 0:47

1 Answer 1

3

You can use explode() and parse_url():

$url   = parse_url('http://example.com/dir1/dir2/dir3/dir4/');

$path  = explode('/',$url['path']);

$path  = array_filter($path); //remove empty value from array

print_r($path); //output: Array ( [1] => dir1 [2] => dir2 [3] => dir3 [4] => dir4 ) 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Zulkhaery! Just what I needed. Cheers!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.