Home > Article > Backend Development > How to get filename without extension using PHP? (code example)
How to get the file name without extension? The following article will introduce to you how to use PHP to remove the extension from the file name and return the file name without the extension. I hope it will be helpful to you. [Video tutorial recommendation: PHP tutorial]
##Method 1: Use the built-in function pathinfo()
The pathinfo() function will return the file path information in the form of an array, including: dirname, basename, extension, filename.Basic syntax:
pathinfo(path,options)Parameter path: Indicates the path to be checked. Parameter options: can be omitted, indicating the array elements to be returned, the default value is all. Can have the following values: ● PATHINFO_DIRNAME: Only returns the directory name (dirname). ●PATHINFO_BASENAME: Returns the complete file name (basename), that is, the file name with extension. ●PATHINFO_EXTENSION: Returns only the extension (extension)●PATHINFO_FILENAME: Returns the file name without extension (filename).
Code example:
<?php // 用文件名初始化变量 $file = 'demo.html'; // 仅提取文件名 $x = pathinfo($file, PATHINFO_FILENAME); // 输出 echo $x; ?>Output:
demo
Note: If the file name contains a full path, only no File name with extension.
Method 2: Use the built-in function basename()
The basename() function returns the file name part of the path, that is, without the extension The file name; this function is used to return the trailing name component of path as a string.Basic syntax:
basename(path,suffix)Parameter path: Indicates the path to be checked. Parameter suffix: can be omitted, indicating the file extension. If the suffix parameter is not omitted, the file name without extension is output.
Code example:
<?php $file = 'demo/filename.txt'; $x = basename($file, '.txt'); echo $x; ?>Output:
filename
Method 3: Use the substr() and strrpos() functions
Code example:
<?php $file = 'PHP.pdf'; $x = substr($file, 0, strrpos($file, '.')); echo $x; ?>Output:
PHPNote: If the file name contains a full path, the full path without extension and file name. Example: If $file = 'demo/PHP.pdf', then return:
demo/PHPThe above is the entire content of this article, I hope it will be helpful to everyone's learning. For more exciting content, you can pay attention to the relevant tutorial columns of the PHP Chinese website! ! !
The above is the detailed content of How to get filename without extension using PHP? (code example). For more information, please follow other related articles on the PHP Chinese website!