Idka-80
Idka-80

Reputation: 13

Get values from url with PHP

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.

Upvotes: 0

Views: 80

Answers (3)

Álvaro González
Álvaro González

Reputation: 146630

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, '/'));

Upvotes: 0

Piyush Sapariya
Piyush Sapariya

Reputation: 538

@idka-80 try this,

$url_components = parse_url($url);
echo "<pre>";
print_r(array_filter(explode("/",$url_components['path'])));

Upvotes: 6

azibom
azibom

Reputation: 1944

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;

Upvotes: 0

Related Questions