remove extension from file [duplicate] - php

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.

Related

How to slice an input value? [duplicate]

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.

ucfirst capitalizing the second letter when run at command line

I have a log method which saves to a file that is named the same as the script calling it, only with a capital first letter, which works sometimes, but other times capitalizes the second letter (I can't see any pattern as to when it does what but it's always consistent, meaning that file A will always either be initial capped or second letter capped, it's not arbitrary).
Here's my code...
function logData($str){
$filePath = $_SERVER["SCRIPT_FILENAME"];
$dir = substr($filePath, 0, strrpos($filePath, "/") + 1);
$fileName = substr($filePath,strrpos($filePath, "/")+1);
$fileName = preg_replace('/\w+$/','log',$fileName);
$fileName = ucfirst($fileName);
$fHandle = fopen( $dir.$fileName , "a");
$contents = fwrite($fHandle, $str ."\n");
fclose($fHandle);
}
Does anyone have any thoughts on what could be causing such an odd behavior *some of the time?
I know I can brute force it with a strtoupper on the first char and then append the rest of the string, but I'd really like to understand what (if anything) I'm doing wrong here.
This is probably a bug further up the code, where you calculate the $dir and $filename. If the path has a slash or not... a probably solution is .
if (strpos('/', $filePath) === false) {
$dir = '';
$fileName = $filePath;
} else {
$dir = substr($filePath, 0, strrpos($filePath, "/") + 1);
$fileName = substr($filePath,strrpos($filePath, "/")+1);
}
But echo those values out and concetrate there
You can forcefully downcase the file name before capitalizing the first letter. That is if all what you care about is capitalizing the first letter.
$fileName = ucfirst(strtolower($fileName));
On the docs for ucfirst it says (with my emphasis):
Returns a string with the first character of str capitalized, if that
character is alphabetic.
Depending on where you execute this script SCRIPT_FILENAME will return different results. Could it be possible that you execute the script from a different path, thus giving SCRIPT_FILENAME a relative path?
To test this theory, I ran the script below from some of your possible execution paths and saw possible examples include the prefix "./" and "/" which would likely not be considered as having alphabetic first characters.
<?php
error_reporting(E_ALL);
echo $_SERVER["SCRIPT_FILENAME"];
?>

Get extension from filename like variable [duplicate]

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];

Truncating a string from last till a character is encountered in PHP

I have a string with a path like so:
C:/myfolder/mysubfolder/myfile.doc
I need to truncate the string to become:
myfile.doc
Needless to say, I have a list of such paths with different lengths and different folder depths. What I need is something like trancating the rest of the string beginning from the last of the string till the first / is encountered.
How can I achieve this in PHP.
Many thanks
$path = 'C:/myfolder/mysubfolder/myfile.doc':
$filename = basename($path);
echo $filename; // "myfile.doc"
See Manual "basename()". For more detailed information about a path see pathinfo()
You can use the basename() function for this.
echo basename("C:/myfolder/mysubfolder/myfile.doc");
Output:
myfile.doc
Note that this doesn't exactly do what you described, because for these inputs:
/etc/
.
it would return
etc
.
So an (untested) alternative could be:
$fullname = "C:/myfolder/mysubfolder/myfile.doc";
$parts = explode("/", $fullname);
$filename = $parts[count($parts)-1];
echo $filename;
If you mean you want the filename segment, you can use basename()
http://php.net/manual/en/function.basename.php

PHP: How to remove unnecessary dots in filename on file upload?

I have a script to upload files with PHP.
I already do some cleaning to remove ugly characters.
I would also like to to remove dots in the filename, EXCEPT for the last one, which indicates the file extension.
Anyone has an idea how I could do that.?
For example, how would you get
$filename = "water.fall_blue.sky.jpg";
$filename2 = "water.fall_blue.sky.jpeg";
to return this in both cases..?
water.fall_blue.sky
Use pathinfo() to extract the file name (the "filename" array element is available since PHP 5.2); str_replace() all the dots out of it; and re-glue the file extension.
Here's an example of how this can be done:
<?php
$string = "really.long.file.name.txt";
$lastDot = strrpos($string, ".");
$string = str_replace(".", "", substr($string, 0, $lastDot)) . substr($string, $lastDot);
?>
It converts filenames like so:
really.long.file.name.txt -> reallylongfilename.txt
Check here: example
[Edit] Updated script, dot position is cached now
FILENAME = this/is(your,file.name.JPG
$basename=basename($_FILES['Filedata']['name']);
$filename=pathinfo($basename,PATHINFO_FILENAME);
$ext=pathinfo($basename,PATHINFO_EXTENSION);
//replace all these characters with an hyphen
$repar=array(".",","," ",";","'","\\","\"","/","(",")","?");
$repairedfilename=str_replace($repar,"-",$filename);
$cleanfilename=$repairedfilename.".".strtolower($ext);
RESULT = this-is-your-file-name.jpg

Categories