Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Break URL into parts and locate the ID (longest part)

Tags:

regex

php

I have a URL:

$url = 'https://docs.google.com/spreadsheets/d/1ljJpZDiayzMLhIJ-JDSIJjdjdY_xg3RrUDljFVRB0Qk/edit?usp=sharing#helloworld';

I want to get the ID out of this URL. The ID is always the longest part of the URL 1ljJpZDiayzMLhIJ-JDSIJjdjdY_xg3RrUDljFVRB0Qk, so my approach is to target the longest part.

How can I break this URL into parts and grab the longest part? I want to ignore the query variable part ?usp=sharing#helloworld when breaking it into parts.

What I've tried so far

I tried a preg_match_all() approach with a regex that doesn't seem to break the URL properly:

$regex = '/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/';
$url = 'https://docs.google.com/spreadsheets/d/1ljJpZDiayzMLhIJ-JDSIJjdjdY_xg3RrUDljFVRB0Qk/edit?usp=sharing#helloworld';
$result = preg_match_all($regex, $url, $matches);
print($matches);
like image 909
Goodbye World Avatar asked Jan 04 '23 21:01

Goodbye World


2 Answers

You can use the function explode to split a string in a array.

And the function parse_url()to get the path of your URL.

$path = parse_url($url, PHP_URL_PATH);
$array = explode("/", $path);

edit

If you want to include query-variables you can add this three lines.

parse_str($query,$queries);
$query = parse_url($url, PHP_URL_QUERY);
$array = array_merge($array, $queries);

Now you can look wich part is the longest.

$id = "";
foreach($array as $part){
    if(strlen($id) < strlen($part)) {
        $id = $part;
    }
}
like image 56
Y4roc Avatar answered Jan 06 '23 12:01

Y4roc


$url = 'https://docs.google.com/spreadsheets/d/1ljJpZDiayzMLhIJ-JDSIJjdjdY_xg3RrUDljFVRB0Qk/edit?usp=sharing#helloworld';
$partURL=explode('/', $url);
$lengths = array_map('strlen', $partURL);
$maxLength = max($lengths);
$index = array_search($maxLength, $lengths);
echo $partURL[$index];

Returns: 1ljJpZDiayzMLhIJ-JDSIJjdjdY_xg3RrUDljFVRB0Qk

like image 24
Charly Avatar answered Jan 06 '23 11:01

Charly