0

我有以下类型的网址

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

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

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

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

我只需要从 url 检索数字。

例如,

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

4

4 回答 4

4

看看parse_url

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

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

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

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

$id = $path[0]; // 1
于 2012-05-04T16:57:00.707 回答
2

鉴于提供的信息,这将满足您的要求......这不是我所说的强大解决方案:

$url = $_SERVER['PATH_INFO']; // e.g.: "http://domain.com/1/index.php";
$pieces = explode("/", $url);
$num = $pieces[3];
于 2012-05-04T16:57:18.423 回答
1
  • 用正斜杠 ( explode('/', $_SERVER['REQUEST_PATH']);)分割服务器路径
  • 从头开始删除空条目
  • 取第一个元素
  • 确保它是一个整数(intval()或简单的(int)强制转换)。

无需为此使用正则表达式。

于 2012-05-04T16:57:00.230 回答
0

您使用 preg_match() 匹配域并获取第一个段。

$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.
于 2012-05-04T17:09:36.530 回答