-1

The last question was marked as a duplicate so I'm reopening since $_SERVER['REQUEST_URI']: isnt what I'm looking for because it displays the entire path.

I need to just display the name of the 2nd folder alone without the path, without forward slashes and without the pagename

Here is the structure of the URL: http://example.com/sub/THISFOLDER/page.php

the domain will change, so I'm looking for a solution that will work for any domain as long as it targets the 2nd folder.

What I want to do is something like this:

if THISFOLDER is named folder1 then { include("header2.php"); }

Joe Bobby
  • 2,803
  • 10
  • 40
  • 59

3 Answers3

1

To fetch the current folder name use this method:

$arr = explode('/', dirname(__FILE__));
$whatyouneed = $arr[count($arr)-1];
Roberto Anić Banić
  • 1,411
  • 10
  • 21
1
<?php
$str = 'http://example.com/sub/THISFOLDER/page.php';
$parts = parse_url($str);
$folders = explode('/', $parts['path']);
var_dump($folders[2]);

Output:

string(10) "THISFOLDER"

I used parse_url so it will work easily regardless of the exact url structure.

Jessica
  • 7,075
  • 28
  • 39
0

If you always want to get the last folder before the php page. (Even if it is not the second you can use this code).

<?php
$thisPath = $_SERVER['PHP_SELF'];;
$pattern = '/(\W+)\/(\w+)\/(\w+)/';
$replacement = '$2';
echo preg_replace($pattern, $replacement, $string);
?>

Sorry, I don't have a php instance spun up to actually test this, but the way it should work is this: Looking at it from back to front: It will find normal word characters and hit the slash, that is accounted for by "/". Then it will look for more normal characters. The '/' is covered, then it will look for any possible non-white space character to cover the rest. You want the middle portion.

Questionable
  • 768
  • 5
  • 26