Here include some concept to get the file extension using php
Using patinfo() function
To find file extension using php pathinfo() function is more useful.
In this method file extension can found from url and if has many dots.
In this method file extension can found from url and if has many dots.
<?php $a="http://www.yahoo.com/taslim.html.php"; function file_extension($filename){ $path_info = pathinfo($filename); return $path_info['extension']; } //output //php ?>Using pathinfo() we also get the parts of url or file location
<?php $path_parts = pathinfo('/www/htdocs/inc/lib.inc.php'); echo $path_parts['dirname'], "\n"; echo $path_parts['basename'], "\n"; echo $path_parts['extension'], "\n"; echo $path_parts['filename'], "\n"; // since PHP 5.2.0 ?>
Using explode()
<?php $filename = "any.file.name.jpeg"; $extension = end(explode(".",$filename)); echo $extension; ?> //output //jpegUsing function we use the explode()
<?php $filename = "any.file.name.jpeg"; function file_ext($file) return end(explode(".",$filename)); } echo file_ext($filename); ?> //output //jpeg
Using sub srting
uses string manipulation to get the extension and grabs the dot(.) character.
<?php $filename = 'filename.blah.txt'; function getFileExtension($filename){ return substr($filename, strrpos($filename, '.')); } echo getFileExtension($filename); ?> //output //txt
<?php $filename = 'filename.blah.txt'; $ext = substr(strrchr($filename, '.'), 1); echo $ext; ?>
<?php $filename = 'filename.blah.txt'; function get_file_extension($file_name){ return substr(strrchr($file_name,'.'),1); } echo get_file_extension($file_name); ?>
Get the file extension using PHP regular expression
<?php $filename = 'filename.pdf'; $ext = preg_replace('/^.*\.([^.]+)$/D', '$1', $filename); echo $ext; ?>
$lt;?php $file = 'sad.asdfasdf.asdfa.sdf.ffff'; preg_match('/\.[^\.]+$/i',$file,$ext); echo $ext[0]; // outputs: //.ffff ?>
$lt;?php $filename="tas.pdf"; $exts = split("[/\\.]", $filename); $n = count($exts)-1; $ext = $exts[$n]; echo $ext; ?>
<?php $filename = 'filename.pdf'; function file_ext($filename) { if( !preg_match('/\./', $filename) ) return ''; return preg_replace('/^.*\./', '', $filename); } echo file_ext($filename); ?>
Get the file extension using PHP regular expression
<?php $filenames = array( 'test.jpg', 'longfilename.html', 'PHP Tutorial from Nashruddin.pdf', 'unusual.name.for.a.file.extension', 'another, weird, file.jpeg', 'my favorite song.mp3' ); foreach ($filenames as $filename) { preg_match("/\.([^\.]+)$/", $filename, $matches); print $matches[1] . '
'; } /* will print: jpg html pdf extension jpeg mp3 */ ?>
No comments:
Post a Comment