PHP: filename without file extension- best way?

前端 未结 4 924
囚心锁ツ
囚心锁ツ 2020-12-10 06:35

I am trying to pull the filename out of a directory without the extension.

I am kludging my way through with the following:

foreach ($allowed_files a         


        
相关标签:
4条回答
  • 2020-12-10 07:14

    PHP has a handy pathinfo() function that does the legwork for you here:

    foreach ($allowed_files as $filename) {
      echo pathinfo($filename, PATHINFO_FILENAME);
    }
    

    Example:

    $files = array(
      'somefile.txt',
      'anotherfile.pdf',
      '/with/path/hello.properties',
    );
    
    foreach ($files as $file) {
      $name = pathinfo($file, PATHINFO_FILENAME);
      echo "$file => $name\n";
    }
    

    Output:

    somefile.txt => somefile
    anotherfile.pdf => anotherfile
    /with/path/hello.properties => hello
    
    0 讨论(0)
  • 2020-12-10 07:14

    try this

    function file_extension($filename){
        $x = explode('.', $filename);
        $ext=end($x);
        $filenameSansExt=str_replace('.'.$ext,"",$filename);
        return array(
            "filename"=>$filenameSansExt,
            "extension"=>'.'.$ext,
            "extension_undotted"=>$ext
            );
    }
    

    usage:

    $filenames=array("file1.php","file2.inc.php","file3..qwe.e-rt.jpg");
    foreach($filenames as $filename){
        print_r(file_extension($filename));
        echo "\n------\n";
    
    }
    

    output

    Array
    (
        [filename] => file1
        [extension] => .php
        [extension_undotted] => php
    )
    
    ------
    Array
    (
        [filename] => file2.inc
        [extension] => .php
        [extension_undotted] => php
    )
    
    ------
    Array
    (
        [filename] => file3..qwe.e-rt
        [extension] => .jpg
        [extension_undotted] => jpg
    )
    
    ------
    
    0 讨论(0)
  • 2020-12-10 07:14

    list($file) = explode('.', $filename);

    0 讨论(0)
  • 2020-12-10 07:14

    Try this:

    $noExt = preg_replace("/\\.[^.]*$/", "", $filename);
    

    Edit in response to cletus's comment:
    You could change it in one of a few ways:

    $noExt = preg_replace("/\\.[^.]*$/", "", basename($filename));
    
    // or
    
    $noExt = preg_replace("/\\.[^.\\\\\\/]*$/", "", $filename);
    

    Yes, PHP needs regex literals...

    0 讨论(0)
提交回复
热议问题