Search code examples
preg-matchextract

Get File ID from Google Drive with PHP


I have been looking for a way to extract the ID of a file in Google Drive, and well both looking for information and some similar functions, I have managed to find this, it works for me, but I hope they can polish it a little more.

    <?php
function get_drive_id_from_url($url)  {
    preg_match('/\/d\/(.+)\//', $url, $result);
    return $result[1];
}

echo get_drive_id_from_url('https://drive.google.com/file/d/FILE_ID/view?usp=sharing');
?>

Solution

  • If you use another delimiter than / you don't have to escape the forward slash. You can make use of \K to forget what is matched so far, followed by matching any character except /

    Then assert a / directly to the right using a positive lookahead.

    As this does not use a capture group, the result is in $result[0].

    /d/\K[^/]+(?=/)
    

    The pattern matches:

    • /d/ Match literally
    • \K Clear the match buffer
    • [^/]+ Match 1+ times any char except / (or [^/\s]+ to also not match a whitespace char)
    • (?=/) Positive lookahead, assert / directly to the right

    See a regex demo and a PHP demo.

    Example code

    function get_drive_id_from_url($url)
    {
        preg_match('~/d/\K[^/]+(?=/)~', $url, $result);
        return $result[0];
    }
    
    echo get_drive_id_from_url('https://drive.google.com/file/d/FILE_ID/view?usp=sharing');
    

    Output

    FILE_ID
    

    The capture group variant of the updated pattern is:

    /d/([^/]+)/
    

    Regex demo