Ben
Ben

Reputation: 1

Get the dynamic number after the last "/" of external url

I want to grab the last dynamic numbers of an external URL.

https://data.aboss.com/v1/agency/1001/101010/events/xxxxxx

$url = https://data.aboss.com/v1/agency/1001/101010/events/;
$value = substr($url, strrpos($url, '/') + 1);
value="<?php echo $value; ?>"

result should be xxxxxx.

Upvotes: -1

Views: 45

Answers (2)

Arleigh Hix
Arleigh Hix

Reputation: 10897

There are many ways to do this, the simplest one-liner would be to use explode:

echo explode("/events/", $url)[1];

Or if something may come after 'events/xxxxxx':

$url = "https://data.aboss.com/v1/agency/1001/101010/events/1524447/other/123456";
echo explode("/", explode("/events/", $url)[1])[0]; // 1524447

You can also use a regex with preg_match:

$url = "https://data.aboss.com/v1/agency/1001/101010/events/1524447/other/123456";
$matches = [];
preg_match("~/events/(\d+)~", $url, $matches); // captures digits after "/events/"
echo($matches[1]); // 1524447

Sandbox

Upvotes: 1

Irfan
Irfan

Reputation: 213

To get the last part from the url, you can use parse_url() and pathinfo() function in PHP. Try following code,

<?php
$url = "https://data.aboss.com/v1/agency/1001/101010/events/xxxxxx";
$path = parse_url($url, PHP_URL_PATH);
$value = pathinfo($path, PATHINFO_FILENAME);

echo $value;

Upvotes: 0

Related Questions