PHP Remove Extension From String

PHP

Nicesnippets

51

19-11-2020


Hi Guys,

Today, i will learn you how to remove extension from string. we will show example of remove extension from string in php. If you’ve got a filename that you need to remove the extension from with PHP, there are a number of ways to do it. Here’s three ways, with some benchmarking.

-> Using an inbuilt function pathinfo

-> Using an inbuilt function basename

-> Using an string functions substr and strrpos

Example 1: Using Pathinfo


Here,The pathinfo() function returns an array containing the directory name, basename, extension and filename.

Syntax:

pathinfo ( $path, $options = PATHINFO_DIRNAME|PATHINFO_BASENAME|PATHINFO_EXTENSION|PATHINFO_FILENAME )

Alternatively, if only one PATHINFO_ constants is passed as a parameter it returns only that part of the full filename.

<?php

// Initializing a variable with filename

$file = 'nameFile.php';

// Extracting only filename using constants

$x = pathinfo($file, PATHINFO_FILENAME);

// Printing the result

echo $x;

?>

Output:

nameFile

Note: If the filename contains a full path, then only the filename without the extension is returned.

Example 2: Using Basename

In this example,The basename() function is used to return trailing name component of path in the form of string. The basename() operates naively on the input string, and is not aware of the actual file-system, or path components such as “..”

Syntax:

basename ( $path, $suffix )

When an extension of file is known it can be passed as a parameter to basename function to tell it to remove that extension from the filename.

<?php

// Initializing a variable

// with filename

$file = 'imageFileName.png';

// Suffix is passed as second

// parameter

$x = basename($file, '.txt');

// Printing the result

echo $x;

?>

Output

imageFileName

Example 3: Using substr and strrpos

Here in this example ,If the filename contains a full path, then the full path and filename without the extension is returned. You could basename() it as well to get rid of the path if needed (e.g. basename(substr($filename, 0, strrpos($filename, ".")))) although it’s slower than using pathinfo.

Syntax:

substr ( $string, $start, $length )

<?php

// Initializing a variable

// with filename

$file = 'filename.pdf';

// Using substr

$x = substr($file, 0, strrpos($file, '.'));

// Display the filename

echo $x;

?>

Output:

filename

Note: If the filename contains a full path, then the full path and filename without the extension is returned.