我希望通过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];
答案 0 :(得分:0)
我认为ID会在$matches[0]
中。
但是这个正则表达式模式会匹配任何最后一个数字的url。 E.g。
http://differentdomain.com/whatever/7
也许这对您来说已经足够了,如果没有,请更详细地描述您的用例。
答案 1 :(得分:0)
使用它:
return $id3 = $parts[count($parts) - 3];
答案 2 :(得分:0)
PHP提供了parse_url()函数,它按照RFC 3986
中所述的组件拆分网址$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,'/'));