【问题标题】:return specific part of URL返回 URL 的特定部分
【发布时间】:2015-01-17 11:54:35
【问题描述】:

我想通过 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];

【问题讨论】:

标签: php


【解决方案1】:

我认为 id 应该是$matches[0]。 但是这个正则表达式模式会匹配任何最后带有数字的 url。例如

http://differentdomain.com/whatever/7

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

【讨论】:

    【解决方案2】:

    使用它:

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

    【讨论】:

      【解决方案3】:

      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,'/'));
      

      【讨论】:

        猜你喜欢
        • 2012-09-06
        • 1970-01-01
        • 2018-09-20
        • 1970-01-01
        • 2023-04-04
        • 1970-01-01
        • 2014-11-25
        • 1970-01-01
        • 2015-12-16
        相关资源
        最近更新 更多