Ojejku
Ojejku

Reputation: 9

How to get part of url before last slash with PHP?

I have URL like

https://example.com/something/this-is-my-part/10448887

and want to have

this-is-my-part

only.

Is there an option for this?

Upvotes: 0

Views: 1578

Answers (3)

Leigh Bicknell
Leigh Bicknell

Reputation: 872

// Remove final slash if it exists
$string = rtrim($string, '/');
// Explode the string into an array
$parts = explode('/', $string);
// Echo 2nd to last item
echo $parts[count($parts) - 2];

Upvotes: 0

jpschroeder
jpschroeder

Reputation: 6916

Sure:

$url = "https://example.com/something/this-is-my-part/10448887";
$path = parse_url($url, PHP_URL_PATH);
$segments = explode("/", $path);
echo $segments[2];

Upvotes: 0

Rolando Cruz
Rolando Cruz

Reputation: 2784

Something like this should work:

$path = parse_url($url, PHP_URL_PATH);
$parts = explode('/', $path);
$part = $parts[count($parts) - 2];

Upvotes: 1

Related Questions