0

I have a url something like this:

http://example.com/a/b/c.php

If I do a $_SERVER['HTTP_HOST'], I get example.com

If I do a $_SERVER['REQUEST_URI'], I get a/b/c.php

But I want output as example.com/a/ I am assuming I will have to use some regex, not exactly sure how.

Any suggestions are welcome. Thank you :)

Anusha
  • 647
  • 11
  • 29

2 Answers2

2

I would use explode:

<?php
$url = $_SERVER['HTTP_HOST'] . '/' . explode('/',$_SERVER['REQUEST_URI'])[1];
echo $url;
?>
Neil
  • 14,063
  • 3
  • 30
  • 51
2

Or In regex way, you may do it like this:

^http(?:s)?:\/\/\K([^\/]+\/[^\/]+\/).*$

Demo

Sample Source (Run Here)

$re = '/^http(?:s)?:\/\/\K([^\/]+\/[^\/]+\/).*$/m';
$str = 'http://example.com/a/b/c.php';
preg_match($re, $str, $matches);
echo $matches[1];
Mustofa Rizwan
  • 10,215
  • 2
  • 28
  • 43