views:

43

answers:

5

Hi there,

I'm trying to get a users ID from a string such as:

http://www.abcxyz.com/123456789/

To appear as 123456789 essentially stripping the info up to the first / and also removing the end /. I did have a look around on the net but there seems to be so many solutions but nothing answering both start and end.

Thanks :)

Update 1

The link can take two forms: mod_rewrite as above and also "http://www.abcxyz.com/profile?user_id=123456789"

+3  A: 

I would use parse_url() to cleanly extract the path component from the URL:

$path = parse_URL("http://www.example.com/123456789/", PHP_URL_PATH);

and then split the path into its elements using explode():

$path = trim($path, "/"); // Remove starting and trailing slashes
$path_exploded = explode("/", $path);

and then output the first component of the path:

echo $path_exploded[0]; // Will output 123456789

this method will work in edge cases like

  • http://www.example.com/123456789?test
  • http://www.example.com//123456789
  • www.example.com/123456789/abcdef

and even

  • /123456789/abcdef
Pekka
if there is only the number, you can just trim: `echo trim(parse_url('http://www.abcxyz.com/123456789/', PHP_URL_PATH), '/');`
Gordon
Thats great, that works fine. Could I also get this to work in the case of "http://www.abcxyz.com/profile?user_id=123456789"?
lethalMango
@lethal yes, you can get the `user_id` part by using `PHP_URL_QUERY` in the `parse_url` call. See the manual page for all possible combinations.
Pekka
@lethal in case where you are using `PHP_URL_QUERY` you might want to use `parse_str(parse_url('http://www.abcxyz.com/profile?user_id=123456789', PHP_URL_QUERY), $parts);`. That would parse the query string into `$parts` which you could then access with `$parts['user_id']` to get the value.
Gordon
Thanks a lot guys :)
lethalMango
Note that using `trim($path, '/')` will remove *all* empty path segments at the begin and end.
Gumbo
+1  A: 
$string = 'http://www.abcxyz.com/123456789/';
$parts = array_filter(explode('/', $string));
$id = array_pop($parts);
Nev Stokes
A: 

If there is no other numbers in the URL, you can also do

echo filter_var('http://www.abcxyz.com/123456789/', FILTER_SANITIZE_NUMBER_INT);

to strip out everything that is not a digit.

That might be somewhat quicker than using the parse_url+parse_str combination.

Gordon
A: 

If the ID always is the last member of the URL

$url="http://www.abcxyz.com/123456789/";
$id=preg_replace(",.*/([0-9]+)/$,","\\1",$url);
echo $id;
elzapp
A: 

Hi,

If your domain does not contain any numbers, you can handle both situations (with or without user_id) using:

<?php

$string1 = 'http://www.abcxyz.com/123456789/';
$string2 = 'http://www.abcxyz.com/profile?user_id=123456789';

preg_match('/[0-9]+/',$string1,$matches);
print_r($matches[0]);


preg_match('/[0-9]+/',$string2,$matches);
print_r($matches[0]);


?>
XViD