skip to Main Content

I’m trying to get values from a url using php. With basename I only get the last part but i need the part before that as well.

This is the domain: http://mydomain.nl/first/second/third/

$url = parse_url($entry['source_url']);
$urlFragments = explode('/', $url);
$second = $urlFragments[0];
$third = $urlFragments[1];

I need to use part second and part third.

3

Answers


  1. This script can help you
    First of all, to make it simple I remove http:// part and then explode it with / and get a different part of the data which is separated by /

    <?php
    
    $url = "http://mydomain.nl/first/second/third/";
    $url = str_replace("http://", "", $url);
    $urlFragments = explode('/', $url);
    
    $yourDomain = $urlFragments[0];
    $first = $urlFragments[1];
    $second = $urlFragments[2];
    $third = $urlFragments[3];
    
    echo $first . ", " . $second . ", " . $third;
    
    Login or Signup to reply.
  2. @idka-80 try this,

    $url_components = parse_url($url);
    echo "<pre>";
    print_r(array_filter(explode("/",$url_components['path'])));
    
    Login or Signup to reply.
  3. As you can tell from the fatal error, you’re making a wrong assumption about how parse_url() works:

    Fatal error: Uncaught TypeError: explode(): Argument #2 ($string) must be of type string, array given

    If you only want a specific fragment, you need to tell which one:

    $url = parse_url($entry['source_url'], PHP_URL_PATH);
    // ^ Also give it a better name, such as `$path`
    

    You also possibly want to discard leading and trailing slashes:

    $urlFragments = explode('/', trim($url, '/'));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search