Home >Backend Development >PHP Tutorial >How Can I Easily Extract Filenames Without Extensions in PHP?
Getting a filename without its extension in PHP can be a tedious task, especially if you rely on complex regex patterns. But there's a simpler and more efficient way to do it using the powerful pathinfo() function.
The pathinfo() function provides a comprehensive way to parse a file path into its individual components, including the filename, extension, directory, and more. To extract the filename without the extension, simply use the following code:
$filename = pathinfo($filepath, PATHINFO_FILENAME);
For example, if $filepath contains the value /var/www/my_file.txt, the above code will assign my_file to the $filename variable.
Here are some additional examples from the PHP manual:
$path_parts = pathinfo('/www/htdocs/index.html'); echo $path_parts['dirname'], "\n"; echo $path_parts['basename'], "\n"; echo $path_parts['extension'], "\n"; echo $path_parts['filename'], "\n"; // filename is only available since PHP 5.2.0 // Output: /www/htdocs index.html html index
You can also use the pathinfo() function to extract only specific parts of the file path. For instance, to get only the extension, use this code:
$extension = pathinfo($filepath, PATHINFO_EXTENSION); // outputs 'txt'
So, next time you need to get a filename without its extension in PHP, remember the pathinfo() function. It's an elegant and efficient way to parse file paths into their individual components.
The above is the detailed content of How Can I Easily Extract Filenames Without Extensions in PHP?. For more information, please follow other related articles on the PHP Chinese website!