Getting an identifier from an exploding url

I currently have the following code.

$file_id = 'https://skyvault.co/show/file?filename=6N2viQpwLKBIA6'; $parts = parse_url($file_id); $path_parts = explode('/', $parts[path]); $secret = $path_parts[3]; print $secret; 

You can see that I'm trying to explode / and it does not return a result. I am looking for it by simply returning file , and I need it to return 6N2viQpwLKBIA6 , so how could I get this identifier?

+5
source share
3 answers

Is it possible for you to do this quickly if the URL is always the same for all elements?

 $URLComp = explode("show/file?filename=", $file_id); $secret = $URLComp[1]; print $secret; 

The main reason is that there may be cases with or without www , then with or without https .

+1
source

parse_url , but you need to specify a query index. Repeat it like this:

 $file_id = 'https://skyvault.co/show/file?filename=6N2viQpwLKBIA6'; $parts = parse_url($file_id); $path_parts = explode('=', $parts['query']); $secret = $path_parts[1]; print $secret; 
+4
source

If you need to use parse_url for any reason, you can use the query component instead of path as suggested by @CodieGodie .

However, if you treat this url as a string, you can ignore parse_url and just work with it just like a string.

 $file_id = 'https://skyvault.co/show/file?filename=6N2viQpwLKBIA6'; $parts = explode('/', $file_id); $lastPart = end($parts); $varParts = explode('=', $lastPart);//also explode('?', $lastPart) if you want "filename=" $secret = end($varParts); print $secret; 

Note. This code will work if your string always has the same format as: " https://example.com/path/path/path?varName=varValue 'in just 1 var at the end of the URL.

0
source

Source: https://habr.com/ru/post/1242003/


All Articles