php:在URL中检索数字

php:在URL中检索数字,php,regex,Php,Regex,我有以下类型的url 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中检索号码 比如说, 当我访问时,它必须返回1。 通过正斜杠拆分服务器路径(explode(“/”,$\u server['REQUEST\u path']);) 从开头删除空条目 以第一个元素为例 确保它是整数(

我有以下类型的url

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中检索号码

比如说,

当我访问时,它必须返回1。

  • 通过正斜杠拆分服务器路径(
    explode(“/”,$\u server['REQUEST\u path']);
  • 从开头删除空条目
  • 以第一个元素为例
  • 确保它是整数(
    intval()
    ,或简单的
    (int)
    cast)
无需为此使用正则表达式。

请查看

编辑:查看
$\u服务器['REQUEST\u URI']
,以获取当前URL。用它代替
$url['path']

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

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

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

根据提供的信息,这将满足您的要求。。。这不是我所说的稳健解决方案:

$url = $_SERVER['PATH_INFO']; // e.g.: "http://domain.com/1/index.php";
$pieces = explode("/", $url);
$num = $pieces[3];
使用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.

1 2 3 4是真正的目录吗?那么我建议Daniel Bidulock回答。$url应该从地址栏中检索,其他部分工作正常$url=“;$pieces=explode(“/”,$url);$num=$pieces[3];echo$num;很高兴为您提供帮助,并感谢您接受的答案(尽管我认为@Rocket值得更多)$url应从地址栏中检索,其他部分正在工作fine@PankajjKumar:尝试
$\u服务器['PATH\u INFO']
而不是
$url['PATH']
。如果这不起作用
var\u dump($\u服务器)
,其中一个值将具有路径(
'/1/index.php'
)。$\u服务器['PATH\u INFO']返回nothing@PankajjKumar:尝试
$\u服务器[“改为请求_URI“]
(或
$\u SERVER[“SCRIPT\u NAME”]
,或
$\u SERVER[“PHP\u SELF”]
)使用
var\u dump($\u SERVER)
,若要查看有哪些值,我忘了您需要哪一个。@PankajjKumar:什么不返回?该页面上有什么代码?$url=“$片段=分解(“/”,$url)$num=$pieces[3];echo$num;
$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.