user2988099
user2988099

Reputation: 1

Remove the extension from a file name and include all files in directory

I looked on the forums but did not find what I need. I need help to delete the extension from the file name, and include all files for example (php files) from a directory, and show you examples.

This code work

$name = 'file.php';    
$fileName= pathinfo($name, PATHINFO_FILENAME );

echo "Name: {$fileName}";

Results:

Name: file

but how do I get this with several files included in the folder

<?php          
$dir = "/dir1/dir2/dir3/dir4/";
$phpfiles = glob($dir . "*.php");

foreach ($phpfiles as $phpfile){

     echo '<li><a href="'.$phpfile.'">'.basename($phpfile,".php").'</a></li>'; 
}
output
1.php
2.php
3.php
4.php
-----------------
how to insert path info in this script so that all files are included without extensions.
?>

Upvotes: 1

Views: 476

Answers (2)

bansi
bansi

Reputation: 56982

If you want to display the filenames only you can use @zavg's suggestion (just add a .). If you want to actually modify the array for later use you can use array_map.

$dir = "/dir1/dir2/dir3/dir4/";
$phpfiles = glob($dir . "*.php");
//using basename
$phpfiles=array_map(function($f){return basename($f, ".php");},$phpfiles);
//Or Using pathinfo
//$phpfiles=array_map(function($f){return pathinfo($f, PATHINFO_FILENAME );},$phpfiles);
foreach ($phpfiles as $phpfile){
     echo '<li><a href="'.$dir.$phpfile.'">'.$phpfile.'</a></li>'; 
}

Upvotes: 0

Raggamuffin
Raggamuffin

Reputation: 1760

By using pathinfo function...??

<?php          
$dir = "/dir1/dir2/dir3/dir4/";
$phpfiles = glob($dir . "*.php");

foreach ($phpfiles as $phpfile){
     echo '<li><a href="'.$phpfile.'">'.pathinfo($phpfile, PATHINFO_FILENAME).'</a></li>'; 
}

Upvotes: 1

Related Questions