Extract first URL Segment from full URL

10,696

Solution 1

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 (/)

Solution 2

$page = explode('/', substr($_SERVER['REQUEST_URI'], 1), 2);
echo str_replace("-"," ", $page[0]);

Solution 3

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

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

Share:
10,696
Nyxynyx
Author by

Nyxynyx

Hello :) I have no formal education in programming :( And I need your help! :D These days its web development: Node.js Meteor.js Python PHP Laravel Javascript / jQuery d3.js MySQL PostgreSQL MongoDB PostGIS

Updated on June 16, 2022

Comments

  • Nyxynyx
    Nyxynyx almost 2 years

    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