php:检索URL中的数字

时间:2012-05-04 16:52:38

标签: php regex

我有以下类型的网址

http://domain.com/1/index.php

http://domain.com/2/index.php

http://domain.com/3/index.php

http://domain.com/4/index.php

我只需要从网址中检索数字。

例如,

当我访问http://domain.com/1/index.php时,它必须返回1.

4 个答案:

答案 0 :(得分:4)

查看parse_url

$url = parse_url('http://domain.com/1/index.php');

编辑:查看$_SERVER['REQUEST_URI'],获取当前网址。使用它而不是$url['path']

然后你可以在$url['path']上拆分/,并获得第一个元素。

// use trim to remove the starting slash in 'path'
$path = explode('/', trim($url['path'], '/')); 

$id = $path[0]; // 1

答案 1 :(得分:2)

根据提供的信息,这将按照你的要求行事......这不是我称之为强有力的解决方案:

$url = $_SERVER['PATH_INFO']; // e.g.: "http://domain.com/1/index.php";
$pieces = explode("/", $url);
$num = $pieces[3];

答案 2 :(得分:1)

  • 通过正斜杠(explode('/', $_SERVER['REQUEST_PATH']);
  • 拆分服务器路径
  • 从头开始删除空条目
  • 采取第一个元素
  • 确保它是整数(intval()或简单的(int)强制转换)。

不需要使用正则表达式。

答案 3 :(得分:0)

您使用preg_match()来匹配域并获得第1段。

$domain = http://www.domain.com/1/test.html

preg_match("/http:\/\/.*\/(.*)\/.*/", "http://www.domain.com/1/test.html");

echo $matches[1];  // returns the number 1 in this example.