How to remove file extension in php?

Member

by nicola , in category: PHP , 3 years ago

How to remove file extension in php?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by dmitrypro77 , 3 years ago

@nicola You can try to use pathinfo() function in PHP to remove file extension from the file, here is code as example how it works:


1
2
3
4
5
6
7
8
<?php

$file = 'test.txt';

$fileName = pathinfo($file, PATHINFO_FILENAME);

// Output: test
echo $fileName;
by jeanie_reilly , 2 years ago

@nicola 

To remove the file extension from a string in PHP, you can use the pathinfo() function to retrieve the extension and then use the str_replace() function to replace the extension with an empty string.


Here's an example code snippet that demonstrates how to remove the file extension in PHP:

1
2
3
4
5
6
<?php
$file = "example.txt";
$extension = pathinfo($file, PATHINFO_EXTENSION); // get the extension
$filename = str_replace("." . $extension, "", $file); // remove the extension
echo $filename; // outputs "example"
?>


In this example, we first define a string $file containing the filename with extension. We then use the pathinfo() function to retrieve the extension by passing the constant PATHINFO_EXTENSION as the second argument. We store the extension in the $extension variable.


Finally, we use the str_replace() function to replace the extension (including the dot) with an empty string. We store the resulting string in the $filename variable and then output it to the screen using the echo statement.

Related Threads:

How to remove .php extension from url?
How to remove .php extension from url in nginx?
How to remove .php extension from url and trailing slash in nginx?
How to remove file name with extension from file path field in postgresql?
How to check file extension in PHP?