Jump to content

PHP - Renaming everything after the X characters to "..."


Gamerz

Recommended Posts

Hey all,

 

So I'm working on this php uploader. What I'm trying to do is prevent the uploaded filename from becoming too long. So in this example, let's say...rename after the 8th character.

 

---

Example:

Original Filename: JohnAccountInformationTest.txt

PHP Renamed Filename: JohnAcco....txt

----

 

So basically, after the 8th character, PHP should replace everything else in the filename to just "..." AND the .txt should stay the same, and not get changed....how would I do this?

 

Also, one more thing. As I have realized, users who upload a file like: Kevin'sAccount.txt will result in the file being called Kevin/'sAccount.txt will totally messes up the system. How would I delete the automatically "/" that is being added to the filename everytime there is a single quote added?

This is untested but should work:

 

$filename = "JohnAccountInformation.txt";
$pieces = explode(".", $filename); // Get segments (name and extension).
$extension = $pieces[(count($pieces)-1)]; // Get last value in array (In case the filename is John.Account.Info.txt).
$i = 0;
$filename = "";
foreach($pieces as $part) {
    $i++;
    if($i !== count($pieces)) { // Check if it is not the extension.
        if($i > 1) $filename .= ".";
        $filename .= $part; // Recreate the actual filename.
    }
}
if(strlen($filename) >  { // Check if it is more than 8 characters.
    $filename = trim(substr($filename, 0, 5)) . "..."; // Set the trimmed filename (so that there is no space before the ellpisis).
}
$filename = stripslashes($filename . "." . $extension); // Add the extension and remove slashes.
echo $filename;

hmm. looking at matal999's post i see i failed to account for dots within.

$fn='John.Account.Info.txt';
$f=explode(".",$fn);
$e=array_pop($f);
$fs = implode(".", $f);
$ct=strlen($fs);
if($ct>
$nf=substr($fs, 0, ;
$new="$nf....$e";
echo "$new";

 

 

HTH

Teamatomic

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.