-1

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.

pppery
  • 3,731
  • 22
  • 33
  • 46
Ben
  • 1
  • 2
  • 1
    where is the URL coming from? – Tom J Nowell Feb 17 '23 at 16:27
  • Give two or more examples of URLs and the corresponding desired results. The code provided cannot result `xxxxxx `, since `$url` does not contain `xxxxxx `. – fusion3k Feb 17 '23 at 16:36
  • Hi fusion3k, what I am trying is to check if there are events. When its true the url is something like this ```https://data.aboss.com/v1/agency/1001/101010/events/1234567``` and when there are no events there is nothing after events/ – Ben Feb 17 '23 at 16:42

2 Answers2

1

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

Arleigh Hix
  • 9,990
  • 1
  • 14
  • 31
0

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;
Irfan
  • 215
  • 2
  • 8
  • Hi Irfan, thanks for your answer. Its working but it does not check the external url. The result is xxxxxxx but not the dynamic number of the url –  Feb 17 '23 at 15:57
  • I don't understand what is you mean by dynamic number? What do you expect the result in the mentioned url? Is not xxxxxx you want? – Irfan Feb 17 '23 at 16:14
  • No it is something like 1524447 but its dynamic so what I need are the dynamic generated numbers after url/events/... –  Feb 17 '23 at 16:18
  • Ben you haven't said where this `$url` is coming from, I've tested the code posted here and it does indeed extract the part that comes after `events/`. Nothing in your question mentioned validating, and there is no way to get a number out of a URL that has no numbers. You should edit your question to provide more context and to specify the entire question with no hidden parts – Tom J Nowell Feb 17 '23 at 16:26
  • Hi Tom, what I am trying is to check if there are events. When its true the url is something like this https://data.aboss.com/v1/agency/1001/101010/events/1234567 and when there are no events there ist nothing – Ben Feb 17 '23 at 16:40