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

I have a url:

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

      

I want to get the id of this url. The ID is always the longest part of the URL 1ljJpZDiayzMLhIJ-JDSIJjdjdY_xg3RrUDljFVRB0Qk

, so my approach targets the longest part.

How can I split this URL into parts and grab the longest part? I want to ignore the query variable ?usp=sharing#helloworld

when splitting into parts.

What I have tried so far

I've tried a preg_match_all()

regex approach that doesn't seem to break the url correctly:

$regex = '/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/';
$url = 'https://docs.google.com/spreadsheets/d/1ljJpZDiayzMLhIJ-JDSIJjdjdY_xg3RrUDljFVRB0Qk/edit?usp=sharing#helloworld';
$result = preg_match_all($regex, $url, $matches);
print($matches);

      

+3


source to share


4 answers


You can use a function explode

to split a string in an array.

And a function parse_url()

to get the path to your url.

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

      


change



If you want to include query variables, you can add these three lines.

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

      


Now you can see which part is the longest.

$id = "";
foreach($array as $part){
    if(strlen($id) < strlen($part)) {
        $id = $part;
    }
}

      

+8


source


$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

+1


source


You can use this regex: ^.*\/d\/(.*)\/.*$

For example:

$regex = '/^.*\/d\/(.*)\/.*$/';
$url = 'https://docs.google.com/spreadsheets/d/1ljJpZDiayzMLhIJ-JDSIJjdjdY_xg3RrUDljFVRB0Qk/edit?usp=sharing#helloworld';
$result = preg_match_all($regex, $url, $matches);
print_r($matches);

      

as a result you will get:

Array
(
    [0] => Array
        (
            [0] => https://docs.google.com/spreadsheets/d/1ljJpZDiayzMLhIJ-JDSIJjdjdY_xg3RrUDljFVRB0Qk/edit?usp=sharing#helloworld
        )

    [1] => Array
        (
            [0] => 1ljJpZDiayzMLhIJ-JDSIJjdjdY_xg3RrUDljFVRB0Qk
        )

)

      

0


source


you can use substr (string, start, length)

0


source







All Articles