7

How can the first URL segment be extracted from the full URL? The first URL segment should be cleaned to replace the - with a space .

Full URL

http://www.domain.com/River-Island/River-Island-T-Shirt-with-Triangle-Girl-Print/Prod/pgeproduct.aspx?iid=2516020

Desired Outpput

River Island
Nyxynyx
  • 61,411
  • 155
  • 482
  • 830

5 Answers5

14

You can use:

$url = 'http://www.domain.com/River-Island/River-Island-T-Shirt-with-Triangle-Girl-Print/Prod/pgeproduct.aspx?iid=2516020';
$parsed = parse_url($url);
$path = $parsed['path'];
$path_parts = explode('/', $path);
$desired_output = $path_parts[1]; // 1, because the string begins with slash (/)
Teneff
  • 30,564
  • 13
  • 72
  • 103
2
$page = explode('/', substr($_SERVER['REQUEST_URI'], 1), 2);
echo str_replace("-"," ", $page[0]);
Green Black
  • 5,037
  • 1
  • 17
  • 29
1

Try this: /http:\/\/[^\/]+\/([^\/]+)/i

See here: http://regex101.com/r/lB9jN7

Firas Dib
  • 2,743
  • 19
  • 38
  • Slightly modified this to exclude the first segment and get everything else in nginx conf like this `^\/[^\/]+\/(.*)`. This helps to build seo-friendly urls with independent sub-directory controllers. Thumbs up! – Christos Lytras Jul 15 '17 at 22:46
0
$path = parse_url($url, PHP_URL_PATH);
$first = substr($path, 0, strpos($path, '/'));

Check the docs for these three functions. Maybe you'll have to strip a slash from the beginning of the path, I'm not sure.

Daniel M
  • 3,369
  • 20
  • 30
-2

have you using CodeIgniter ...???then it could be

$this->uri->segment(segment number of url);

and its need to load uri library in Controller

GautamD31
  • 28,552
  • 10
  • 64
  • 85