Which regular expression will detect if the url file has the extension

My actual URLs might look something like this:

http://someurl.com/some/path/file.pdf
or 
http://someurl.com/some/path/file.pdf?param=value
or 
http://someurl.com/some/path/file.pdf?param=value&second=val

where the file extension may be .pdf or another extension, for example .jpg or .psd, or nothing at all.

I have a url stored without someurl.com part, so some/path/file.pdfpart of the url

How can I use regex to find out the file extension, if present? Is regex the right tool for this?

+5
source share
4 answers

I would use parse_url()and pathinfo(). These are the most correct functions for work.

$url = 'http://someurl.com/some/path/file.pdf?param=value';

$path = parse_url($url, PHP_URL_PATH);

$ext = pathinfo($path, PATHINFO_EXTENSION);

var_dump($ext); // string(3) "pdf"

Take a look at CodePad.org .

You can use a regular expression, but it will be harder to follow with it.

+10

, , HTTP HEAD. Regex , , .

:

http://someurl.com/some/path/file (, * nix), .

+1

: PHP parse_url:

$path = parse_url($url, PHP_URL_PATH);
$extension = ($pos = strrpos($path, '.')) ? substr($path, $pos) : "";
+1

, parse_url.

$url = parse_url('http://example.com/path/to/file.php?param=value');

$extension = substr($url['path'], strrpos($url['path'], '.') + 1);
echo $extension; // outputs "php"

http://php.net/parse-url

http://php.net/substr

http://php.net/strrpos

+1

All Articles