【问题标题】:exploding a file name to separate the name and extension won't work in PHP?分解文件名以分隔名称和扩展名在 PHP 中不起作用?
【发布时间】:2012-05-12 14:26:00
【问题描述】:

我正在构建一个返回字符串的类,该字符串将自动包含文件夹中的文件,有点像 HTML 文件的加载器。

下面是要调用的方法:

function build_external_file_include($_dir){
    $_files = scandir($_dir);
    $_stack_of_file_includes = "";//will store the includes for the specified file.
foreach ($_files as $ext){
    //split the file name into two;
    $fileName = explode('.',$ext, 1);//this is where the issue is.

    switch ($fileName[1]){
        case "js":
            //if file is javascript
             $_stack_of_file_includes =  $_stack_of_file_includes."<script type='text/javascript' src='".$dir.'/'.   $ext ."'></script>";

            break;
        case "css";//if file is css
             $_stack_of_file_includes =  $_stack_of_file_includes."<link rel=\"stylesheet\" type=\"text/css\" href=\"".$dir.'/'. $ext."\" />";
            break;
        default://if file type is unkown
             $_stack_of_file_includes =  $_stack_of_file_includes."<!-- File: ".  $ext." was not included-->";
    }


}
return $_stack_of_file_includes;
}

所以,这运行没有任何错误。但是,它没有做它应该做的事情……或者至少我打算做的事情。从技术上讲,

$fileName[1] 应该是扩展名js

$fileName[0]应该是文件名main

但是

$fileName[0]main.js

爆炸不识别.

提前谢谢你。

【问题讨论】:

  • $fileName = explode('.',$ext, 1); 更改为 $fileName = explode('.',$ext);
  • 我建议你使用pathinfo()而不是explode
  • @felipe.. 你会用这些文件名做什么jquery-.1.7.1.min.js
  • diEcho,您好,感谢您的关注!这个特定的类为 CSS 和 JS 文件构建了一组 HTML 外部文件引用。正如您在此处看到的,脚本设置为遍历指定目录中的文件并返回一个字符串,该字符串具有引用外部文件的 HTML 标记,在本例中为该文件夹中的文件。

标签: php filenames explode period scandir


【解决方案1】:

您正在强制生成的数组包含 1 个元素,这会导致它具有整个文件名。

explode( '.', $ext, 1 )

应该是

explode( '.', $ext );

证明:http://codepad.org/01DLpo6H

【讨论】:

  • 哇,我现在感觉好傻。不过,我不能感谢你。
【解决方案2】:

您已将爆炸限制为产生 1 数组条目,因此它永远无法执行任何操作:

print_r(explode('.', 'a.b', 1));
Array
(
    [0] => a.b
)

限制应该至少为 2。或者,更好的是,您应该使用 pathinfo() 函数,它可以为您正确处理文件名组件。

【讨论】:

    猜你喜欢
    • 2012-12-19
    • 1970-01-01
    • 1970-01-01
    • 2013-04-08
    • 2011-05-17
    • 1970-01-01
    • 2012-02-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多