Welcome to the PHP basename() tutorial! In this lesson, we'll explore the basename() function, one of the essential PHP string functions that helps you work with file paths. By the end of this tutorial, you'll be able to extract file names from various path formats and understand when to use basename(). Let's dive in!
basename()? πThe basename() function is used to extract the base name (file name) from a given path. This function is particularly useful when working with directories, files, or URLs containing directories and files.
basename(string $path): stringIn the above function signature, $path is the path of the file or directory you want to extract the base name from. The function returns the base name as a string.
$path = "/example/documents/file.txt";
$filename = basename($path);
echo $filename; // Output: file.txtIn the above example, we have a file path "/example/documents/file.txt", and we're extracting the base name using basename(). The output will be "file.txt".
$url = "https://www.codeyourcraft.com/example/file.html";
$filename = basename($url);
echo $filename; // Output: file.htmlIn this example, we're extracting the base name from a URL, which contains a directory ("example") and a file extension (.html). The output will be "file.html".
You can use basename() in combination with the pathinfo() function to remove the file extension:
$path = "/example/documents/file.txt";
$path_info = pathinfo($path);
$filename = $path_info['filename'];
echo $filename; // Output: fileIn this example, we're using pathinfo() to get an associative array containing information about the path, such as the directory, extension, and base name. Then, we're extracting the base name ("file") from the array.
What does the PHP `basename()` function do?
That's all for today's PHP basename() tutorial! Keep practicing and stay tuned for more in-depth PHP lessons on CodeYourCraft. Happy coding! π»π