返回 URL 的特定部分


return specific part of URL

我想通过php返回URL的特定部分,例如,如果URL是:

http://website.com/part1/part2/part3/detail/page_id/number/page/2

http://website.com/part1/part2/part3/detail/page_id/number/page/3 

我想要退货号码。

可以吗?

$pattern = "/'d+$/";
$input = "http://website.com/part1/part2/part3/detail/page_id/number/page/2";
preg_match($pattern, $input, $matches);
$post_id = $matches[8];

我认为 id 会$matches[0].但是这种正则表达式模式会匹配末尾带有数字的任何 url。例如

http://differentdomain.com/whatever/7

也许这对您来说已经足够了,如果没有,请更详细地描述您的用例。

使用它:

return $id3 = $parts[count($parts) - 3];

PHP 提供了 parse_url() 函数,该函数按 RFC 3986 中所述的组件拆分 url

$s = 'http://website.com/part1/part2/part3/detail/page_id/number/page/2';
$u = parse_url($s);
// gives you
array (size=3)
'scheme' => string 'http' (length=4)
'host' => string 'website.com' (length=11)
'path' => string '/part1/part2/part3/detail/page_id/number/page/2' (length=47)

如果您只想获取特定组件,该函数可以接受标志作为第二个参数(例如。 PHP_URL_PATH)对此有所帮助。

$u = parse_url($s, PHP_URL_PATH);
// gives you
string '/part1/part2/part3/detail/page_id/number/page/2' (length=47)

您现在可以创建一个段数组,并用它详细说明您的逻辑:

$segments = explode('/',trim($u,'/'));