Jump to content

Seperate number from end of url


frobak

Recommended Posts

Hi

 

I need to take the number off of the end of a url and do some processing with it.

 

so for example:

 

www.something.com/something/10001

 

i will need to seperate them into 2 different variables, for example:

 

$var1 = www.something.com/something/

$var2 = 10001

 

is this possible?

 

Thanks

Link to comment
https://forums.phpfreaks.com/topic/252829-seperate-number-from-end-of-url/
Share on other sites

$var2 = substr(strrchr(__FILE__, '/'), 1);
$var1 = substr(__FILE__, 0, -(strlen($var2)));

 

I believe this will work, but it's untested, I'm just trying to work it out in my head so I strongly suggest testing it first and if it's not giving you what you expect, report back on your results.

Actually, __FILE__ might not do what I'm thinking.

 

In any event, your 2nd problem is more straight forward. You can simply replace __FILE__ with wherever the user input is stored... IE. if it was submitted in a text box named "url" you'd replace __FILE__ with $_POST['file']

 

But you should make sure to validate user input in advance!

 

$var2 = substr(strrchr($_POST['url'], '/'), 1);
$var1 = substr($_POST['url'], 0, -(strlen($var2)));

You might be able to make a more dynamic solution from this:

function segment($index = 1)
{
$segments = explode ('/', $_SERVER['REQUEST_URI']);

if (!empty($segments)) {
	array_shift($segments);

	return $segments[$index - 1];
}

return null;
}

 

To use, simply count the number of "segments" after your domain and there you go. So in "www.something.com/something/10001", doing echo segment(2) would echo "10001".

 

EDIT: By the way I didn't rigorously test this, just a push in the right direction.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.