获取外部URL中最后一个斜杠后面的动态数字。

huangapple go评论74阅读模式
英文:

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

问题

我想提取外部URL的最后动态数字部分。

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

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

结果应该是xxxxxx。


<details>
<summary>英文:</summary>

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

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

```php
$url = https://data.aboss.com/v1/agency/1001/101010/events/;
$value = substr($url, strrpos($url, &#39;/&#39;) + 1);
value=&quot;&lt;?php echo $value; ?&gt;&quot;

result should be xxxxxx.

答案1

得分: 1

使用explode有多种方法来实现这一目标,最简单的一行代码如下所示:

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

或者,如果在'events/xxxxxx'之后可能有其他内容:

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

您还可以使用preg_match来使用正则表达式:

$url = "https://data.aboss.com/v1/agency/1001/101010/events/1524447/other/123456";
$matches = [];
preg_match("~/events/(\d+)~", $url, $matches); // 捕获"/events/"之后的数字
echo($matches[1]); // 1524447
英文:

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

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

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

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

You can also use a regex with preg_match:

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

Sandbox

答案2

得分: 0

你可以使用PHP中的parse_url()pathinfo()函数来获取URL的最后一部分。尝试以下代码,

<?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;
英文:

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

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

echo $value;

huangapple
  • 本文由 发表于 2023年2月17日 23:38:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/75486830.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定