Pankajj Kumar
Pankajj Kumar

Reputation: 5

php : Retrieving number in the URL

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

Answers (4)

gen_Eric
gen_Eric

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

thenetimp
thenetimp

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

Daniel Bidulock
Daniel Bidulock

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

tdammers
tdammers

Reputation: 20721

  • split the server path by forward slashes (explode('/', $_SERVER['REQUEST_PATH']);)
  • remove empty entry from the beginning
  • take the first element
  • make sure it is an integer (intval(), or a simple (int) cast).

No need to use regular expressions for this.

Upvotes: 1

Related Questions