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.
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);
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;
}
}
$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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With