7.5 Parsing the Parts of a Filename
TechniqueUse PHP's built-in pathinfo() function, which provides all the information you need. <?php $pinfo = pathinfo("/home/sterling/monkey.php"); print "Directory name is: $pinfo[dirname]\n"; print "Filename is: $pinfo[basename]\n"; print "Ending is: $pinfo[extension]\n"; ?> CommentsPHP's pathinfo() function will give you all the information you need about the different elements of a filename (in a portable manner ”i.e., it works with both Win32 and UNIX filenames). Note that the "extension" element of the array returned by pathinfo() is only present if the file has an extension, otherwise it is not present. You can also access only individual elements of a path name via the pathinfo constants (PATHINFO_DIRNAME, PATHINFO_BASENAME and PATHINFO_EXTENSION) : <?php $path = "/home/sterling/monkey.php"; $dirname = pathinfo($path, PATHINFO_DIRNAME); print "Directory name is: $dirname\n"; ?> |