views:

452

answers:

3

I have this code:

    function ShowFileExtension($filepath)
{
    preg_match('/[^?]*/', $filepath, $matches);
    $string = $matches[0];

    $pattern = preg_split('/\./', $string, -1, PREG_SPLIT_OFFSET_CAPTURE);

    if(count($pattern) > 1)
    {
        $filenamepart = $pattern[count($pattern)-1][0];
        preg_match('/[^?]*/', $filenamepart, $matches);
        return strtolower($matches[0]);
    }
}

If I have a file named my.zip, this function returns .zip.

Now I want to do the reverse, I want the function to return my without the extension.

tip:the file is not in the server its just name from variable

+6  A: 

No need for all that. Check out pathinfo(), it gives you all the components of your path.

Example from the manual:

<?php
$path_parts = pathinfo('/www/htdocs/index.html');

echo $path_parts['dirname'], "\n";
echo $path_parts['basename'], "\n";
echo $path_parts['extension'], "\n";
echo $path_parts['filename'], "\n"; // since PHP 5.2.0
?>

and alternatively you can get only certain parts like

echo pathinfo('/www/htdocs/index.html', PATHINFO_EXTENSION); // outputs html
Pekka
doh. you beat me to it by 3 seconds
Gordon
Why was this downvoted? The answer is absolutely correct. pathinfo operates on strings, so it doesn't matter if the file is actually on the server or not.
Gordon
@Pekka I've added an example for usage of options. Hope you don't mind. This should really be the accepted answer.
Gordon
@Gordon Cheers! And edit away, that's perfectly fine.
Pekka
+4  A: 

As an alternative to pathinfo(), you can use

  • basename() — Returns filename component of path

Example from PHP manual

$path = "/home/httpd/html/index.php";
$file = basename($path);         // $file is set to "index.php"
$file = basename($path, ".php"); // $file is set to "index"

You have to know the extension to remove it in advance though.

However, since your question suggests you have the need for getting the extension and the basename, I'd vote Pekka's answer as the most useful one, because it will give you any info you'd want about the path and file with one single native function.

Gordon
thanks very much
moustafa
A: 

@Gordon basename will work fine if you know the extension, if you dont you can use explode:

$filename = current(explode(".", $file));
fire
Please direct comments to me with the comment function below my answer. The most appropriate function for this is `pathinfo`, which is why I gave `basename` as an alternative only. There is no need to reinvent `pathinfo` with regex or `explode`.
Gordon
its will not work if the file like that my.file.2.1.zip
moustafa