You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP正则表达式负前瞻匹配文件名:优化JS文件压缩匹配规则

Optimizing JS File Matching with PHP Regex Negative Lookahead

Hey Joel! Let's fix up that regex to skip already minified JS files using negative lookahead—this way you won't waste resources re-compressing files that are already compressed (like your jquery-ui.min.js example).

The Problem with Your Current Regex

Your existing regex /\.js$/i works for matching all .js files, but it doesn't distinguish between uncompressed .js files and pre-minified ones like .min.js. That means you might be running your compressor on files that don't need it.

Using Negative Lookahead to Exclude Minified Files

Negative lookahead ((?!pattern)) lets you define a condition that must not be true for the match to succeed. For your case, we want to match any .js file that does not end with .min.js.

Here's the updated regex:

/^(?!.*\.min\.js$).*\.js$/i

Let's break down what each part does:

  • ^: Anchors the match to the start of the string (ensures we check the entire filename)
  • (?!.*\.min\.js$): The negative lookahead—this says "the string must not end with .min.js". The .* matches any characters leading up to that suffix, and $ anchors it to the end.
  • .*\.js$: Matches any string that ends with .js (our original matching rule)
  • i: Makes the match case-insensitive (so .JS files are also included if needed)

Updated PHP Code

Swap out your original regex with the new one, and your code will now skip pre-minified files:

if (preg_match('/^(?!.*\.min\.js$).*\.js$/i', $script)) { 
    $asset = $this['asset']->createFile($script); 
    if ($asset->getPath()) { 
        $script = $this['asset']->cache(basename($script), $asset, array('JsCompressor'), $options)->getUrl(); 
    } 
}

Extending to Exclude Other Compressed Suffixes

If you have other pre-compressed file patterns (like .bundle.js or .compressed.js), you can expand the negative lookahead to include those too:

/^(?!.*\.(min|bundle|compressed)\.js$).*\.js$/i

This will skip any file ending with .min.js, .bundle.js, or .compressed.js.

内容的提问来源于stack exchange,提问作者Joel M

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:19:23