在不同情况下获取部分网址


Get Part Of Url In different Cases

>我今天想问你,如果你帮我改进我的代码,我正在尝试获取网址的 id,它总是在/id/之后,在这个例子中我需要不带引号的"9050102"。

网址可以有不同的方式:

.site.com/Descreption-Text-Etc/id/9050102
site.com/Descreption-Text-Etc/id/9050102
site.com/bi/product/9050102
.site.com/bi/product/9050102

我的代码:

$foo = explode('/', $url); //Extracing ID
$id = strtoupper($foo[3]); //ID

我注意到在某些情况下它不起作用,不知道为什么所以在那之后我添加了:

if (!$id) { 
$id = strtoupper($foo[2]); //Making Sure ID Found
} 

你能帮我改进它以 100% 准确且始终找到它吗?

您可以使用 end 函数来获取数组中的最后一个元素。它将数组指针设置为最后一个元素并返回其值。

$foo = explode('/', $url); //Extracing ID
$id = strtoupper(end($foo)); //ID
if(isset($id) && strlen($id)==10) {
//code
}
$foo = explode('/', $url);
//count the $foo array
$count = count($foo);
//the last index will be minus 1
$id = $foo[$count-1];

试试这个

<?php
$url = "site.com/Descreption-Text-Etc/id/9050102";
echo substr($url, strrpos($url, "/") + 1);

如果您确定 ID 将始终位于最后一个位置,则可以使用 end 函数获取数组的最后一个元素:

$id = end($foo);
if ($id && isset($id[9])) {
   // this means that the ID exists and has at least 10 characters
}