my file name are being stored in a variable $file_name... how can i remove the extension and just have the name only? is there something other than strcmp that i can use... that doesn't seem to do it
Asked
Active
Viewed 977 times
7 Answers
9
Use pathinfo.
<?php
$path_parts = pathinfo('/www/htdocs/inc/lib.inc.php');
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
?>
Note: If you're not on PHP >= 5.2 use this to compose the filename
$path_parts['filename'] = substr($path_parts['basename'], 0, -1*strlen($path_parts['extension'])-1);

Alin Purcaru
- 43,655
- 12
- 77
- 90
-
+1 for the built-in function rather than more complicated and error prone alternatives – Mark Baker Dec 13 '10 at 09:35
2
You can do:
$file_name_no_ext = pathinfo($file_name , PATHINFO_FILENAME);

codaddict
- 445,704
- 82
- 492
- 529
1
You should take a look at the pathinfo()
function.

Salman A
- 262,204
- 82
- 430
- 521

AgentConundrum
- 20,288
- 6
- 64
- 99
-
@Salman A: Exactly what was so offensive about the link I posted? Does it really matter which mirror is linked? – AgentConundrum Dec 13 '10 at 09:36
-
@Salman: I could've done that myself. I just wanted to know *why* you thought it necessary. – AgentConundrum Dec 13 '10 at 09:57
-
There were two answers containing same link, different hostnames so I made them consistent. – Salman A Dec 13 '10 at 10:15
1
substr($file_name, 0, -4);

Luca Bernardi
- 4,191
- 2
- 31
- 39
-
not really. the pathinfo solution given elsewhere on this site would return "archive.tar" in this case. Afaik there is no reliable solution to cope with double extensions ;) – Gordon Dec 13 '10 at 23:26
0
Similar to @fire, but more robust in the face of multiple dots:
$comps = explode('.', $filename);
unset($comps[count($comps) - 1]);
$ext = implode('.', $comps);

David Weinraub
- 14,144
- 4
- 42
- 64
-3
I use:
$file_name = current(explode(".", $file_name));

fire
- 21,383
- 17
- 79
- 114
-
-
This will give you anything until the first `.`. What happens for `my.strange.path/i.like.dots.php`? – Alin Purcaru Dec 13 '10 at 09:34
-
this will fail if the filename contains dot. Something like: this.is.a.picture.jpg – Andreas Wong Dec 13 '10 at 09:34