AngularAngularAngular
AngularAngularAngular

Reputation: 3769

String Replace after Last Period

Here I am getting the file name as $fileName

I want to store the file name as

filename_randomnumber.extension

If file name is file.jpg then it will be file_randomnumber.jpg

If file name is test.png then it will be test_randomnumber.png

I use the following code for that

$digits = 6;
$digits = rand(pow(10, $digits-1), pow(10, $digits)-1);
$val = $digits.'_.';
$gen_path = preg_replace("([.]+)", $val, $fileName);  //replacing . with _randomnumber.

I am just replacing the . with random number and _

But the threat is

If the file name has

test.image.png

Then the value will be test_randomnumber.image_randomnumber.png

What i need is i need to replace the right most . found in the file name.

So that the result will be test.image_randomumber.png

How can i do this

Upvotes: 1

Views: 148

Answers (3)

Ja͢ck
Ja͢ck

Reputation: 173562

You can use pathinfo() and sprintf():

function getRandomFileName($fileName)
{
    $info = pathinfo($fileName);

    $digits = 6;
    $digits = rand(pow(10, $digits-1), pow(10, $digits)-1);

    if (isset($info['extension'])) {
        return sprintf('%s_%s.%s', $info['filename'], $digits, $info['extension']);
    } else {
        return sprintf('%s_%s', $info['filename'], $digits);
    }
}

echo getRandomFileName('test.jpg'); // test_838135.jpg

Upvotes: 2

Sulthan Allaudeen
Sulthan Allaudeen

Reputation: 11310

I had a Tiny Workaround which will get your need.

Firstly Explode after last . 'period'

$fileName = implode('.', explode('.', $string, -1));

Secondly get the Extension in the right most of the $fileName

$ext = substr($string, strrpos($string, '.') + 1);

And in Mid your $val shall be concatinated

So, Your Code must be

<?php
$fileName = 'b.a.png';
$string = $fileName;
$fileName = implode('.', explode('.', $string, -1));
$ext = substr($string, strrpos($string, '.') + 1);
$digits = 6;
$digits = rand(pow(10, $digits-1), pow(10, $digits)-1);
$val = $digits.'_.';
echo $fileName.$val.$ext;

Upvotes: 1

user1537366
user1537366

Reputation: 1187

Try this:

$genpath=substr_replace($fileName,"_".$digits,strrpos($fileName,"."),0);
  1. strrpos gets the last position of "." in $fileName.
  2. substr_replace inserts the random number with the underscore into $fileName before the dot.

Assuming the filename has already a dot inside.

Upvotes: 0

Related Questions