0

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.

2
  • Are 1 2 3 4 a real directories? Commented May 4, 2012 at 16:59
  • Then I would suggest Daniel Bidulock answer. Commented May 4, 2012 at 17:08

4 Answers 4

4

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
Sign up to request clarification or add additional context in comments.

6 Comments

$url should be retrieved from adress bar,other part working fine
@PankajjKumar: Try $_SERVER['PATH_INFO'] instead of $url['path']. If that doesn't work var_dump($_SERVER), one of the values will have the path ('/1/index.php').
$_SERVER['PATH_INFO'] returns nothing
@PankajjKumar: Try $_SERVER["REQUEST_URI"] (or $_SERVER["SCRIPT_NAME"], or $_SERVER["PHP_SELF"]) instead. Use var_dump($_SERVER), to see what values there are, I forget which one is the one you need.
@PankajjKumar: What returns nothing? What code is on that page?
|
2

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];

3 Comments

$url should be retrieved from adress bar,,other part is working fine
$url = "domain.com".$_SERVER["REQUEST_URI"]; $pieces = explode("/", $url); $num = $pieces[3]; echo $num;
Happy to help, and thank you for the accepted answer (though I think @Rocket deserves it more)
1
  • 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.

1 Comment

$url = "domain.com".$_SERVER["REQUEST_URI"]; $pieces = explode("/", $url); $num = $pieces[3]; echo $num;
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.