0

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.

2
  • Get path value and use explode() php.net/manual/en/function.explode.php function Commented Jan 25, 2023 at 11:20
  • 1
    parse_url returns an array (at least when used this way) - and feeding an array to explode makes no sense. Commented Jan 25, 2023 at 11:38

3 Answers 3

6

@idka-80 try this,

$url_components = parse_url($url);
echo "<pre>";
print_r(array_filter(explode("/",$url_components['path'])));
Sign up to request clarification or add additional context in comments.

Comments

0

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;

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.