-2

I am trying to grab only the folder structure from path of URL's, and I can't quite work it out.

I have tried using parse_url, but that get's me the whole path, and from there I tried using explode and regex methods, but non of the one's I have tried give me what I'm after.

An example list of URL's would be:

/example.html
/folder/example.html
/example/folder/example.html
/example/folder/two/

and the results I need are:

/
/folder/
/example/folder/
/example/folder/two/

I'm probably just being blind, or having a coders block, so any help would be appreciated.

2 Answers2

0

Check with my code. It will work for you

$actual_link = "$_SERVER[REQUEST_URI]";
$fromPath = pathinfo('http://www.domaiName.com/folder/page_folder/file.php'); 
//for dynamic use $actual_link variable in  pathinfo() function

echo $fromPath['dirname']; 
  • I managed to cut it down even further, as I'm passing the domain from a string, so I only need to do this `echo pathinfo($url, PATHINFO_DIRNAME); }`, Thanks, I didn't even know about the pathinfo() function – Daniel Coates Jun 15 '16 at 12:38
  • Now its working for you right... Keep developing... Good luck –  Jun 15 '16 at 12:45
0

I have found my own solution, sorry for not incuding the code that I had before, oops.

$urls = array('http://example.com/example.html', 'http://example.com/folder/example.html', 'http://example.com/example/folder/example.html', 'http://example.com/example/folder/two/');

foreach ($urls as $url) {
  $url = parse_url($url, PHP_URL_PATH);
  $last_part_position = strrpos($url, "/");
  $url = substr($url, 0, $last_part_position) . '/';
  echo $url.'<br />';
}