7.5 Parsing the Parts of a Filename


7.5 Parsing the Parts of a Filename

You want to split up a file into its different parts, such as the directory path , the filename, and the file extension.

Technique

Use 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"; ?> 

Comments

PHP'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"; ?> 


PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net