note 83341 deleted from function.strrchr by googleguy
| From: | googleguy@php.net | Date: | Tue, 22 Oct 2013 11:00:22 +0000 |
| Subject: | note 83341 deleted from function.strrchr by googleguy | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-197004@lists.php.net to get a copy of this message | ||
Note Submitter: Emmanuel Quiban
----
strrchr is useful also in determining file extensions.
Here is a sample code that determines the file type based on its file extension. This is useful in
displaying the files in your page, without using the database for the file description list.
<?php
/* File Extension Display using arrays
by: Emmanuel Quiban (Philippines)
BSCS 2002, AdU
21-May-2008
*/
// Sample file
$filesample = "Mydocu.doc";
//Array for file description. You can expand the array list further with other file types you want
$filedes = array(
"Microsoft Excel Worksheet",
"Microsoft Word Document",
"Adobe Reader PDF File");
//Array for file extensions. Please take note that positions between the two arrays should be in
sync with each other for correct file description.
$fileext = array(".xls", ".doc", ".pdf");
//This gets the file extension
$ext = strrchr($filesample,'.');
//This conditional statement checks if the file extension given is in the array and matches it with
the file description
if (in_array($ext,$fileext)) {
//Search the array
$ext2 = array_search($ext, $fileext);
//Since the result of the array_search is in integer, you can now assign it as an array
value
$filetype = $filedes[$ext2];
//Show the result
echo $filetype;
} else {
$filetype = "Unknown file type";
}
?>
-----
The output of the script above is:
Microsoft Word Document
Let's say even if the filename looks like "My.Docu.doc", strrchr still gets the value
".doc" because it gets the last occurance of the dot.
-----
You can also make it as a function, like this:
<?php
/* File Extension Display using arrays
by: Emmanuel Quiban (Philippines)
BSCS 2002, AdU
21-May-2008
*/
function getFileType($yourfile){
$filedes = array(
"CompuServe GIF Image",
"JPEG Image",
"Portable Network Graphics (PNG) Image"
);
$fileext = array(".gif",".jpg",".png");
$ext = strrchr($yourfile,'.');
if (in_array($ext,$fileext)) {
$ext2 = array_search($ext, $fileext);
$filetype = $filedes[$ext2];
} else {
$filetype = "Unknown file type";
}
return $filetype;
}
?>