phpregexslug

Extract first URL Segment from full URL


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

Solution

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