简体   繁体   English

什么正则表达式会找出文件 url 是否具有特定扩展名

[英]What regex would find out if file url has certain extension

My valid urls could look more or less 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 could be .pdf, or some other extension like .jpg or .psd, or nothing at all.其中文件扩展名可以是 .pdf,或其他一些扩展名,如 .jpg 或 .psd,或者什么都没有。

I have the url stored without the someurl.com portion, so it's the some/path/file.pdf part of the url我存储的 url 没有 someurl.com 部分,所以它是 url 的some/path/file.pdf部分

How can I use regex to know the file extension if it is present?如果存在文件扩展名,我如何使用正则表达式知道它? Is regex the right tool for this?正则表达式是正确的工具吗?

I would use parse_url() and pathinfo() .我会使用parse_url()pathinfo() These are the most correct functions for the job.这些是工作中最正确的功能。

$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"

See is on CodePad.org .请参阅 CodePad.org

You could use regex, but it will be more difficult to follow.可以使用正则表达式,但会更难以遵循。

You would probably need to do a HTTP HEAD request.您可能需要执行 HTTP HEAD 请求。 Regex would work for sure, but you're not guaranteed to catch all cases.正则表达式肯定会起作用,但不能保证您能捕获所有情况。

For example:例如:

http://someurl.com/some/path/file might a be a text file without extension (like on most *nix systems) and the regex would fail to provide the file extension. http://someurl.com/some/path/file可能是一个没有扩展名的文本文件(就像在大多数 *nix 系统上一样)并且正则表达式将无法提供文件扩展名。

A much better option is PHP's parse_url function:更好的选择是 PHP 的parse_url函数:

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

Don't need regex, we can just use parse_url .不需要正则表达式,我们可以只使用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/parse-url

http://php.net/substr http://php.net/substr

http://php.net/strrpos http://php.net/strrpos

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM