Search code examples
phpstripstr-replace

Removing content from start and end of string (PHP)


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"


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