【问题标题】:Regex to extract file extension from URL正则表达式从 URL 中提取文件扩展名
【发布时间】:2014-10-31 07:38:50
【问题描述】:

我正在寻找与以下 URI 中的 .js 匹配的正则表达式:

 /foo/bar/file.js?cache_key=123

我正在编写一个函数来尝试识别作为参数传入的文件类型。在这种情况下,文件以扩展名.js 结尾并且是一个javascript 文件。我正在使用 PHP 和 preg_match,所以我假设这是一个与 PCRE 兼容的正则表达式。最终,我将在此表达式的基础上进行构建,并能够检查作为 URI 传入的多种文件类型,该 URI 不仅限于 js,还可能是 css、图像等。

【问题讨论】:

    标签: php regex


    【解决方案1】:

    您可以结合使用pathinfo 和正则表达式。 pathinfo 将为您提供扩展名以及 ?cache_key=123,然后您可以使用与 ? 匹配的正则表达式删除 ?cache_key=123 及其后的所有内容:

    $url = '/foo/bar/file.js?cache_key=123';
    
    echo preg_replace("#\?.*#", "", pathinfo($url, PATHINFO_EXTENSION)) . "\n";
    

    输出:

    js
    

    输入:

    $url = 'my_style.css?cache_key=123';
    

    输出:

    css
    

    显然,如果您需要.,只需将其添加到文件扩展名字符串中即可。

    ETA:如果您确实想要一个正则表达式解决方案,这将解决问题:

    function parseurl($url) {
        # takes the last dot it can find and grabs the text after it
        echo preg_replace("#(.+)?\.(\w+)(\?.+)?#", "$2", $url) . "\n";
    }
    
    parseurl('my_style.css');
    parseurl('my_style.css?cache=123');
    parseurl('/foo/bar/file.js?cache_key=123');
    parseurl('/my.dir.name/has/dots/boo.html?cache=123');
    

    输出:

    css
    css
    js
    html
    

    【讨论】:

      【解决方案2】:

      用途:

      .+\.(js|css|etc)[?]?
      

      $matches[1] 中的扩展

      或者你可以使用

      .+\.(js|css|etc)\?
      

      如果总是使用最终的 ?cache...

      【讨论】:

        【解决方案3】:

        DEMO

        代码

        $input_line = '/foo/bar/file.js?cache_key=123';
        
        // lets grab the part part between filename and ?
        preg_match("/\w+\/\w+\/\w+(.*)\?/", $input_line, $output_array);
        
        var_dump($matches);
        
        echo $matches[0]; 
        

        输出

        Array
        (
           [0] => foo/bar/file.js?
           [1] => .js
        )
        

        .js

        如果您事先知道扩展名(白名单方法),您可能会从匹配​​所有(.*) 切换到匹配特定扩展名/.*\.(js|jpg|jpeg|png|gif)/

        preg_match("/.*\.(js|jpg|jpeg|png|gif)/", $input_line, $matches);
        echo $matches[1]; // js
        

        【讨论】:

        • 这个解决方案相当依赖于有一定数量的目录...
        • 真的!结构是 /word/word/word(match)? .也许就足够了。谁知道。总是有 pathinfo()。
        • 您可以使用(\/\w+)* 使目录数量灵活——匹配0 个或多个/\w+
        猜你喜欢
        • 2018-12-29
        • 2013-03-18
        • 1970-01-01
        • 1970-01-01
        • 2011-04-09
        • 2010-09-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多