PHP function to get file extension [duplicate] - php

This question already has answers here:
How to get a file's extension in PHP?
(31 answers)
Closed 2 years ago.
Can anyone help me change this script to use preg_split (recommended substitute by php.net) instead of split which is not used anymore. This function gets the file extension of any uploaded file in the variable $filename.
function findExtension ($filename)
{
$filename = strtolower($filename) ;
$exts = split("[/\\.]", $filename) ;
$n = count($exts)-1;
$exts = $exts[$n];
return $exts;
}

You should just use pathinfo instead:
$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

Why don't u use this function : http://www.php.net/manual/fr/function.finfo-file.php or this one : http://fr2.php.net/manual/fr/function.pathinfo.php
you can also use explode
function findExtension ($filename)
{
$filename = strtolower($filename) ;
$exts = explode(".", $filename) ;
$n = count($exts)-1;
$exts = $exts[$n];
return $exts;
}

Instead of split you can just use explode. As you just want the extension, there's no reason to split by /, just split by the dot and get the last element with array_pop.

I prefer a function David Walsh posted, that uses the "strrchr" function to get the last occurrence of "." in a string.
function get_file_extension($file_name)
{
return substr(strrchr($file_name,'.'),1);
}

If the file extension is the only part you want:
function GetExt($filename) {
return (($pos = strrpos($filename, '.')) !== false ? substr($filename, $pos+1) : '');
}

Perhaps something along these lines?
$string = "some/path_to_a_file.txt";
$pattern = preg_split('/\./', $string, -1, PREG_SPLIT_OFFSET_CAPTURE);

My code will give file extension, removing query strings. pathinfo also return extension with string. so use my code if you want to know the exact file name:
$filename = 'http://doamin/js.jquery.min.js?v1.1.11';
preg_replace('/\?.*/', '', substr(strrchr($filename, '.'), 1));
// output: js

Related

Bulk renaming using regex in Php

I have a folder in a server with a lot of images and I would like to rename some images. Images that contain (1 example:
112345(1.jpg to 112345.jpg. How can I do this using regex in PHP? I have to mention that my knowledge of PHP is very limited and it's the only language that can effectively do the scripting.
preg_match('/\(1/', $entry) will help you.
Also, you need to pay attention to "what if the file has a duplicate after the rename".
$directory = "/path/to/images";
if ($handle = opendir($directory)) {
while (false !== ($entry = readdir($handle))) {
if ($entry != '.' && $entry != '..') {
// Check "(1"
if (preg_match('/\(1/', $entry)) {
// Rename file
$old = $directory . '/' . $entry;
$new = str_replace('(1', '', $old);
// Check duplicate
if (file_exists($new)) {
$extension = strrpos($new, '.');
$new = substr($new, 0, $extension) . rand() . substr($new, $extension); // Basic rand()
}
rename($old, $new);
}
}
}
closedir($handle);
}
If you want only remove some substring from images names you can do this without regex. Use str_replace function to replace substring to empty string.
As example:
$name = "112345(1.jpg";
$substring = "(1";
$result = str_replace($substring, "", $name);
You can use scandir and preg_grep to filter out the files that needs to be renamed.
$allfiles = scandir("folder"); // replace with folder with jpg files
$filesToRename = preg_grep("/\(1\.jpg/i", $allfiles);
Foreach($filesToRename as $file){
Echo $file . " " . Var_export(rename($file, str_replace("(1.", ".", $file));
}
This is untested code and in theory it should echo the filename and true/false if the rename worked or not.
Only use regex for this if you need to assert the position of the substring, e.g. if you have filenames like Copy (1)(1.23(1.jpg a simple string replacement will go wrong.
$re = '/^(.+)\(1(\.[^\\\\]+)$/';
$subst = '$1$2';
$directory = '/my/root/folder';
if ($handle = opendir($directory )) {
while (false !== ($fileName = readdir($handle))) {
$newName = preg_replace($re, $subst, $fileName);
rename($directory . $fileName, $directory . $newName);
}
closedir($handle);
}
The regular expression used searches for the part before and after the file extension, put the pieces into capturing groups, and glue them together again in the preg_replace without the (1.

Get the file extension [duplicate]

This question already has answers here:
How to get a file's extension in PHP?
(31 answers)
Closed 2 years ago.
I'm exploding on "." to get file format and name:
list($txt, $ext) = explode(".", $name);
The problem is that some files have names with dots.
How do I explote on the LAST "." so that I get $name=pic.n2 and $ext=jpg from: pic.n2.jpg?
Use pathinfo:
$pi = pathinfo($name);
$txt = $pi['filename'];
$ext = $pi['extension'];
$name = pathinfo($file, PATHINFO_FILENAME);
$ext = pathinfo($file, PATHINFO_EXTENSION);
http://www.php.net/pathinfo
use this
$array = explode(".", $name);
end($array); // move the internal pointer to the end of the array
$filetype = current($array);
thanks
Use Pathinfo or mime_content_type to get file type information
$filetype = pathinfo($file, PATHINFO_FILENAME);
$mimetype = mime_content_type($file);
Use PHP's pathinfo() function.
See more information here http://php.net/manual/en/function.pathinfo.php
$file_part = pathinfo('123.test.php');
Example:
echo $file_part['extension'];
echo $file_part['filename'];
Output:
php
123.test
<?php
$path = 'http://www.mytest.com/public/images/portfolio/i-vis/abc.y1.jpg';
echo $path."<br/>";
$name = basename($path);
$dir = dirname($path);
echo $name."<br/>";
echo $dir."<br/>";
$pi = pathinfo($path);
$txt = $pi['filename']."_trans";
$ext = $pi['extension'];
echo $dir."/".$txt.".".$ext;
?>
you can write your own function as
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
You might try something like this:
<?php
$file = 'a.cool.picture.jpg';
$ext = substr($file, strrpos($file, '.')+1, strlen($file)-strrpos($file, '.'));
$name = substr($file, 0, strrpos($file, '.'));
echo $name.'.'.$ext;
?>
The key functions are strrpos() which finds the last occurrence of a character (a "." in this case) and substr() which returns a sub string. You find the last "." in the file, and sub string it. Hope that helps.
It is better to use one of the solutions above, but there is also a solution using the explode function:
$filename = "some.file.name.ext";
list($ext, $name) = explode(".", strrev($filename), 2);
$name = strrev($name);
$ext = strrev($ext);
What this solution does is the following:
1. reverse string, so it will look like: txe.eman.elif.emos
2. explode it, you will get something like: $ext = "txe", $name = "eman.elif.emos"
3. reverse each of the variables to get the correct results

PHP RegEx extract filename

I need your help with a RegEx in PHP
I have something like:
vacation.jpg and I am looking for a RegEx which extracts me only the 'vacation' of the filename.
Can someone help me?
Don't use a regex for this - use basename:
$fileName = basename($fullname, ".jpg");
You can use pathinfo instead of Regex.
$file = 'vacation.jpg';
$path_parts = pathinfo($file);
$filename = $path_parts['filename'];
echo $filename;
And if you really need regex, this one will do it:
$success = preg_match('~([\w\d-_]+)\.[\w\d]{1,4}~i', $original_string, $matches);
Inside matches you will have first part of file name.
Better answers have already been provided, but here's another alternative!
$fileName = "myfile.jpg";
$name = str_replace(substr($fileName, strpos($fileName,".")), "", $fileName);
You don't need regex for this.
Approach 1:
$str = 'vacation.jpg';
$parts = explode('.', basename($str));
if (count($parts) > 1) array_pop($parts);
$filename = implode('.', $parts);
Approach 2 (better, use pathinfo()):
$str = 'vacation.jpg';
$filename = pathinfo($str, PATHINFO_FILENAME);

hiding file extension it self

I looking for your help please
I use simple php code like:
$file = $_SERVER["SCRIPT_NAME"];
//echo $file;
$break = Explode('/', $file);
$pfile = $break[count($break) - 1];
echo $pfile;
than output $pfile e.g. fileforme.php
but that i want is output of $pfile become fileforme
because i want use it to:
$txt['fl']= $pfile ;
how to do? or there are any another better way?
You can use pathinfo() and its PATHINFO_FILENAME flag (only available for php 5.2+)
e.g.
$file = $_SERVER["SCRIPT_NAME"];
echo 'file: ', $file, "\n";
echo 'PATHINFO_FILENAME: ', pathinfo($file, PATHINFO_FILENAME);
prints (on my machine)
file: C:\Dokumente und Einstellungen\Volker\Desktop\test.php
PATHINFO_FILENAME: test
See basename in the PHP Manual:
$path = "/home/httpd/html/index.php";
$file = basename($path); // $file is set to "index.php"
$file = basename($path, ".php"); // $file is set to "index"
or use pathinfo if you do not know the extension:
$path_parts = pathinfo('/www/htdocs/index.html');
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
Basically you're looking for the filename without the extension:
$filename = basename($_SERVER["SCRIPT_NAME"], ".php");
Note that this answer is specific for the php extension.
$pfile_info = pathinfo($pfile);
$ext = $pfile_info['extension'];
See pathinfo() for further information.

How can I change a file's extension using PHP?

How can I change a file's extension using PHP?
Ex: photo.jpg to photo.exe
In modern operating systems, filenames very well might contain periods long before the file extension, for instance:
my.file.name.jpg
PHP provides a way to find the filename without the extension that takes this into account, then just add the new extension:
function replace_extension($filename, $new_extension) {
$info = pathinfo($filename);
return $info['filename'] . '.' . $new_extension;
}
substr_replace($file , 'png', strrpos($file , '.') +1)
Will change any extension to what you want. Replace png with what ever your desired extension would be.
Replace extension, keep path information
function replace_extension($filename, $new_extension) {
$info = pathinfo($filename);
return ($info['dirname'] ? $info['dirname'] . DIRECTORY_SEPARATOR : '')
. $info['filename']
. '.'
. $new_extension;
}
You may use the rename(string $from, string $to, ?resource $context = null) function.
Once you have the filename in a string, first use regex to replace the extension with an extension of your choice. Here's a small function that'll do that:
function replace_extension($filename, $new_extension) {
return preg_replace('/\..+$/', '.' . $new_extension, $filename);
}
Then use the rename() function to rename the file with the new filename.
Just replace it with regexp:
$filename = preg_replace('"\.bmp$"', '.jpg', $filename);
You can also extend this code to remove other image extensions, not just bmp:
$filename = preg_replace('"\.(bmp|gif)$"', '.jpg', $filename);
For regex fans,
modified version of Thanh Trung's 'preg_replace' solution that will always contain the new extension (so that if you write a file conversion program, you won't accidentally overwrite the source file with the result) would be:
preg_replace('/\.[^.]+$/', '.', $file) . $extension
Better way:
substr($filename, 0, -strlen(pathinfo($filename, PATHINFO_EXTENSION))).$new_extension
Changes made only on extension part. Leaves other info unchanged.
It's safe.
You could use basename():
$oldname = 'path/photo.jpg';
$newname = (dirname($oldname) ? dirname($oldname) . DIRECTORY_SEPARATOR : '') . basename($oldname, 'jpg') . 'exe';
Or for all extensions:
$newname = (dirname($oldname) ? dirname($oldname) . DIRECTORY_SEPARATOR : '') . basename($oldname, pathinfo($path, PATHINFO_EXTENSION)) . 'exe';
Finally use rename():
rename($oldname, $newname);
Many good answers have been suggested. I thought it would be helpful to evaluate and compare their performance. Here are the results:
answer by Tony Maro (pathinfo) took 0.000031040740966797 seconds. Note: It has the drawback for not including full path.
answer by Matt (substr_replace) took 0.000010013580322266 seconds.
answer by Jeremy Ruten (preg_replace) took 0.00070095062255859 seconds.
Therefore, I would suggest substr_replace, since it's simpler and faster than others.
Just as a note, There is the following solution too which took 0.000014066696166992 seconds. Still couldn't beat substr_replace:
$parts = explode('.', $inpath);
$parts[count( $parts ) - 1] = 'exe';
$outpath = implode('.', $parts);
I like the strrpos() approach because it is very fast and straightforward — however, you must first check to ensure that the filename has any extension at all. Here's a function that is extremely performant and will replace an existing extension or add a new one if none exists:
function replace_extension($filename, $extension) {
if (($pos = strrpos($filename , '.')) !== false) {
$filename = substr($filename, 0, $pos);
}
return $filename . '.' . $extension;
}
I needed this to change all images extensions withing a gallery to lowercase. I ended up doing the following:
// Converts image file extensions to all lowercase
$currentdir = opendir($gallerydir);
while(false !== ($file = readdir($currentdir))) {
if(strpos($file,'.JPG',1) || strpos($file,'.GIF',1) || strpos($file,'.PNG',1)) {
$srcfile = "$gallerydir/$file";
$filearray = explode(".",$file);
$count = count($filearray);
$pos = $count - 1;
$filearray[$pos] = strtolower($filearray[$pos]);
$file = implode(".",$filearray);
$dstfile = "$gallerydir/$file";
rename($srcfile,$dstfile);
}
}
This worked for my purposes.

Categories