Reputation: 5
I have url in the following types
http://domain.com/1/index.php
http://domain.com/2/index.php
http://domain.com/3/index.php
http://domain.com/4/index.php
I need to retrieve only the number from the url .
for example,
when i visit http://domain.com/1/index.php , It must return 1.
Upvotes: 0
Views: 88
Reputation: 227220
Have a look at parse_url
.
$url = parse_url('http://domain.com/1/index.php');
EDIT: Take a look at $_SERVER['REQUEST_URI']
, to get the current URL. Use that instead of $url['path']
.
Then you can split $url['path']
on /
, and get the 1st element.
// use trim to remove the starting slash in 'path'
$path = explode('/', trim($url['path'], '/'));
$id = $path[0]; // 1
Upvotes: 4
Reputation: 9820
You use preg_match() to match the domain and get the 1st segment.
$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.
Upvotes: 0
Reputation: 2354
Given the information provided, this will do what you ask... it's not what I would call a robust solution:
$url = $_SERVER['PATH_INFO']; // e.g.: "http://domain.com/1/index.php";
$pieces = explode("/", $url);
$num = $pieces[3];
Upvotes: 2
Reputation: 20721
explode('/', $_SERVER['REQUEST_PATH']);
)intval()
, or a simple (int)
cast).No need to use regular expressions for this.
Upvotes: 1