This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to extract a file extension in PHP?
I have a variable $filename="filename.ext" or $filename="filena.m.e.ext" or so on.. How can i extract the extension (here ext) from the variable / string? The variable may change or may have more than one dots.. In that case, i want to get the part after the last dot..
see the answer :
$ext = pathinfo($filename, PATHINFO_EXTENSION);
You can use the path info interrogation.
$info = pathinfo($file);
where
$info['extension']
contains the extension
you could define a function like this:
function get_file_extension($filename)
{
/*
* "." for extension should be available and not be the first character
* so position should not be false or 0.
*/
$lastDotPos = strrpos($fileName, '.');
if ( !$lastDotPos ) return false;
return substr($fileName, $lastDotPos+1);
}
or you could use the Spl_FileInfo object built into PHP
You want to use a regular expression:
preg_match('/\.([^\.]+)$/', $filename);
You can test it out here to see if it gets you the result you want given your input.
There are many ways to do this, ie with explode() or with a preg_match and others.
But the way I do this is with pathinfo:
$path_info = pathinfo($filename);
echo $path_info['extension'], "\n";
You could explode the string using ., then take the last array item:
$filename = "file.m.e.ext";
$filenameitems = explode(".", $filename);
echo $filenameitems[count($filenameitems) - 1]; // .ext
// or echo $filenameitem[-1];
Related
This question already has answers here:
How do I replace certain parts of my string?
(5 answers)
Closed 6 years ago.
I have a file in a directory
name.processing and I want rename this file in name.processed
I have this code:
$fn1 = str_replace(".processed", ".processing", $fn);
rename($fn1,$fn);
$fn contain the complete path.
Why the file did not got rename in directory?
I think this is not a duplicate because i know how replace a part of string but i don't know how replace an extension of file in directory
PHP is not always predictable in parameter sequence, you should consult the documentation.
// processing -> processed
// str_replace($search, $replace, $haystack)
$fn_new = str_replace(".processing", ".processed", $fn);
// rename($oldname, $newname)
$rename = rename($fn,$fn_new);
echo "old: $fn, fn_new: $fn_new, rename: ", $rename ? 'success' : 'failure';
http://php.net/manual/en/function.str-replace.php
http://php.net/manual/en/function.rename.php
Edit:
If it still doesn't work: https://stackoverflow.com/search?q=php+rename
Looks like you have the paramters for str_replace backwards.http://php.net/manual/en/function.str-replace.php
Try $fn1 = str_replace(".processing", ".processed", $fn);
This question already has answers here:
How do I get a file name from a full path with PHP?
(14 answers)
Closed 8 years ago.
My input value is just like this: Oppa/upload/default.jpeg
I want to slice the value of an input according by / cause i want to get the image file name. Does anyone know some tricks to do this?
example: i want to get default.png
<input type="text" value="Oppa/upload/default.png" id="fileLink" name="fileLink" />
Use basename():
$path = "Oppa/upload/default.jpeg";
echo basename($path); //will output "default.jpeg"
echo basename($path, '.jpeg'); //will output "default"
The first parameter is the path of which the trailing component will be removed. If the first parameter ends in the optional second parameter, the second parameter will also be cut off.
On Windows, both slash (/) and backslash (\) are used as directory
separator character. In other environments, it is the forward slash
(/).
- PHP manual
You should use basename() PHP function.
This will work for you
$path = "Oppa/upload/default.jpeg";
echo basename($path);
Use pathinfo() php function
$path = "http://domain.tld/Oppa/upload/default.png";
$info = pathinfo ( $path, PATHINFO_BASENAME ); // returns default.png
Yet another solution, using preg_match()
<?php
$path = "http://domain.tld/Oppa/upload/default.png"; // or "C:\\domain.tld\Oppa\upload\default.jpg";
$pattern = '/[\/|\\\\]((?:.(?!\/|\\\\))+)$/';
if(preg_match($pattern, $path, $matches)){
echo $matches[1]; // default.png or default.jpg
}
?>
Note: People claim to have problems using basename() with asian characters
I am supposing that if your image path will not be change from Oppa/upload/ than this Should work using explode :
$str = "Oppa/upload/default.jpeg";
$s= explode("Oppa/upload/",$str);
echo $s[1];
Another Best thing you can do with defining the relative path as a constant, so :
const path = "Oppa/upload/";
$str = "Oppa/upload/default.jpeg";
$s= explode(path,$str);
echo $s[1];
will also work.
This question already has answers here:
Extract domain from url (including the hard ones) [duplicate]
(3 answers)
Closed 9 years ago.
I want to get the domain extension from the url. eg. .com, .net etc.
I have used this:
$extension = pathinfo($_SERVER['SERVER_NAME'], PATHINFO_EXTENSION);
I was just wondering if there was a better way using parse_url?
Use parse_url(). Something like:
$host = parse_url('http://www.google.co.uk/test.html');
preg_match('/(.*?)((\.co)?.[a-z]{2,4})$/i', $host['host'], $m);
$ext = isset($m[2]) ? $m[2]: '';
Edit: Fixed with regex from this answer. Extension like .co.uk are supported too.
You can easily split the requested URI like this:
function tld( $uri ) {
$parts = explode('.', $uri);
return (sizeof($parts) ? ('.' . end($parts)) : false;
}
So you can do this:
if(!tld('googlecom')) // does not contain an ending TLD
if(tld('google.com')) // this is a valid domain name; output: ".com"
Or you can just use:
echo $_SERVER['SERVER_NAME'];
So in my oppinion the most best example of usage is:
echo tld($_SERVER['SERVER_NAME']);
This question already has answers here:
How to get a file's extension in PHP?
(31 answers)
Closed 9 years ago.
I have string "katrina.bhuvnesh.jpg" , I want to get jpg that means substring that matches the last dot(.)
I looked in substr() function but it's not working exactly what I need.
Please give me any function of PHP that matches string from last and returns substring from that point.
Thanks!!
Use pathinfo() like this:
$extension = pathinfo("katrina.bhuvnesh.jpg", PATHINFO_EXTENSION);
You can use 2 function calls:
$filename = 'somefile.sometext.jpg';
$type = end(explode('.', $filename));
// $type is now 'jpg'
Alternatively, you can use substr:
$type = substr($filename, strrpos($filename, '.'));
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How remove extension from string (only real extension!)
I am brand new to php and have a lot to learn! I'm experimenting with MiniGal Nano for our King County Iris Society website. It work quite well for our purposes with one small exception: the photo file name needs to be visible under the thumbnail. I've created a work around, but it shows the extension. I've found code samples of functions but have no idea how to incorporate them into the existing code. Any assistance would be greatly appreciated.
Example link: http://www.kcis.org/kcisphotogallery.php?dir=Iris.Japanese
Many thanks!
There are a few ways to do it, but i think one of the quicker ways is the following
// $filename has the file name you have under the picture
$temp = explode('.', $filename);
$ext = array_pop($temp);
$name = implode('.', $temp);
Another solution is this. I haven't tested it, but it looks like it should work for multiple periods in a filename
$name = substr($filename, 0, (strlen($filename))-(strlen(strrchr($filename, '.'))));
Also:
$info = pathinfo($filename);
$name = $info['filename'];
$ext = $info['extension'];
// Shorter
$name = pathinfo($file, PATHINFO_FILENAME);
// Or in PHP 5.4
$name = pathinfo($filename)['filename'];
In all of these, $name contains the filename without the extension
You can use pathinfo() for that.
<?php
// your file
$file = 'image.jpg';
$info = pathinfo($file);
// from PHP 5.2.0 :
$file_name = $info['filename'];
// before PHP 5.2.0 :
// $file_name = basename($file,'.'.$info['extension']);
echo $file_name; // outputs 'image'
?>
If you know for certain that the file extension is always going to be four characters long (e.g. ".jpg"), you can simply use substr() where you output the filename:
echo substr($filename, 0, -4);
If there's a chance that there will be images with more or less characters in the file extension (e.g. ".jpeg"), you will need to find out where the last period is. Since you're outputting the filename from the first character, that period's position can be used to indicate the number of characters you want to display:
$period_position = strrpos($filename, ".");
echo substr($filename, 0, $period_position);
For information about these functions, check out the PHP manual at http://php.net/substr and http://php.net/strrpos.