Reputation: 575
I have a page where I want to list all of the documents a user has uploaded, and want to remove the extension from each item that is listed.
This list will contain potentially limitless filetypes, so the method that I was using of manually specifying and replacing the extension with nothing, will take too long.
I also tried to do a str_replace
on .*
so that anything after the .
is replaced, but that did not seem to work.
Here's what I have:
<?php
$chkdir = is_dir("/secure/user uploads/".$_SESSION['SESS_MEMBER_ID']."");
$path = "$chkdir/";
foreach (glob("$path*") as $filename) {
$result = str_replace("$path","", $filename);
$result = str_replace(".pdf","", $result);
$result = str_replace(".db","", $result);
echo "<li><a href='" . $filename ."'/>". $result . "</a></li><tr>";
}
?>
You can see near the end that I specified PDF and DB as file extensions to remove, but I want to try a more general approach, and remove all file extensions.
Can anyone advise with this?
Upvotes: 2
Views: 2210
Reputation: 1
Release 5.2 (March 5, 2013) added PATHINFO_FILENAME
constant.
- for filename without path and extension
In 1 line of code:
$filename = pathinfo("$path", PATHINFO_FILENAME);
your:
foreach (glob("$path*") as $filename) {
echo "<li><a href='" . $filename ."'/>". pathinfo($filename, PATHINFO_FILENAME) . "</a></li><tr>";
}
Upvotes: 0
Reputation: 459
<?
$path = "./";
foreach (glob("$path*") as $filename) {
$result = str_replace("$path","", $filename);
$result = strip_ext($result, "php", "js");
echo "<li><a href='" . $filename ."'/>". $result . "</a></li><tr>";
}
function strip_ext($file) {
$args = func_get_args();
for ($i = 1; $i < count($args); $i++) {
$ext = $args[$i];
$ext_pos = strrpos($file, '.' . $ext);
//The extension must exist and be at the end of the file name.
if ($ext_pos != false && $ext_pos + strlen($ext) == strlen($file) - 1) {
return(substr($file, 0, $ext_pos));
}
}
return($file);
}
?>
Upvotes: 0
Reputation: 23091
You can use pathinfo().
From the PHP manual example:
$path_parts = pathinfo('/www/htdocs/inc/lib.inc.php');
echo $path_parts['filename']; // lib.inc
Applied to your situation:
foreach (glob("$path*") as $filename) {
$path_parts = pathinfo($filename);
$result = $path_parts['filename'];
echo "<li><a href='" . $filename ."'/>". $result . "</a></li><tr>";
}
Upvotes: 4
Reputation: 241
Split by '.' and remove last item, then put it back together.
<?php
$chkdir = is_dir("/secure/user uploads/".$_SESSION['SESS_MEMBER_ID']."");
$path = "$chkdir/";
foreach (glob("$path*") as $filename) {
$result = str_replace("$path","", $filename);
$t = explode('.',$result);
if(count($t) > 1) array_pop($t);
$result = implode('.',$t);
echo "<li><a href='" . $filename ."'/>". $result . "</a></li><tr>";
}
?>
Upvotes: 0
Reputation: 745
You can put all possible extension into an array and replace it looping through it. something like: $ext = array(pdf, db, etc ...);
Upvotes: 0