Question

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"

Was it helpful?

Solution

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

OTHER TIPS

$string = 'http://www.abcxyz.com/123456789/';
$parts = array_filter(explode('/', $string));
$id = array_pop($parts);

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;

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.

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


?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top