RegEx - How To Insert String Before File Extension
No need to use regex. This will do it:
$extension_pos = strrpos($filename, '.'); // find position of the last dot, so where the extension starts
$thumb = substr($filename, 0, $extension_pos) . '_thumb' . substr($filename, $extension_pos);
How can I insert text before the file extension with JavaScript?
I did manage to rework this answer to do the job. It looks like this and it works as expected.
image = 'https://cdn.shopify.com/s/files/1/0919/5078/products/DSC_9782-processed_9bef16cb-7700-48d9-ad6d-f9a350e7f6c7.jpg?v=1579953393';
image = image.replace(/(\.[\w\d?=_-]+)$/i, '_small$1');
Insert a string before the extension in a filename
If we assume that an extension is any series of letters, numbers, underscore or dash after the last dot in the file name, then:
filename = filename.replace(/(\.[\w\d_-]+)$/i, '_large$1');
Append string at the end of url before extension
You can make use of pathinfo
function:
$prod['item_image_url'] = "new-thumb-01.jpg";
$fileparts = pathinfo($prod['item_image_url']);
$bigFileName = $fileparts['filename'] . "-big." .$fileparts['extension'];
$bigFileName
holds new-thumb-01-big.jpg
Regex to append date to a strings with file extension and also without file extensions
Use this regex instead :
str.replace(/(?=\.[^\.]+$)|(?<=^[^\.]+$)/, "_123");
Test it on regex101!
Explanations:
- the
|
separates the cases where there is an extension (like .doc, left part:(?=\.[^\.]+$)
) or no extension (right part:(?<=^[^\.]+$)
). - With extension: get the position of the last dot before the end, and insert the additional string before the match (using lookahead).
- Without extension: if there is no dot in the whole string before the end, just insert the text at the end (using a lookbehind).
PowerShell insert a string into a filename, just before the extension
If you have obtained the report file as FileInfo object by perhaps using Get-Item
or Get-ChildItem
, you'll find that object has convenient properties you can use to create a new filename with the date included:
# assume $ReportName is a FileInfo object
$Backups = "D:\Backups\Reports"
# I'm creating a new filename using the '-f' Format operator
$NewName = '{0}_{1:yyyy-MM-dd__HH-mm}{2}' -f $ReportName.BaseName, (Get-Date), $ReportName.Extension
$ReportBackup = Join-Path -Path $Backups -ChildPath $NewName
If however $ReportName
is just a string that only holds the filename, you can do:
$ReportName = "MyReport-en.csv"
$Backups = "D:\Backups\Reports"
$baseName = [System.IO.Path]::GetFileNameWithoutExtension($ReportName)
$extension = [System.IO.Path]::GetExtension($ReportName)
$NewName = '{0}_{1:yyyy-MM-dd__HH-mm}{2}' -f $baseName, (Get-Date), $extension
$ReportBackup = Join-Path -Path $Backups -ChildPath $NewName
P.S. It is always risky to simply use .Replace()
on a filename because that doesn't allow you to anchor the substring to replace, which is needed, because that substring may very well also be part of the name itself.
Also, the string .Replace()
method works case-sensitive.
This means that
'My.csvReport-en.csv'.Replace(".csv", "_$(Get-Date -Format 'yyyy-MM-dd__HH-mm').csv")
would fail (returns My_2022-04-15__13-36.csvReport-en_2022-04-15__13-36.csv
)
and
'MyReport-en.CSV'.Replace(".csv", "$(Get-Date -Format 'yyyy-MM-dd__HH-mm').csv")
would simply not replace anything because it cannot find the uppercase .CSV
..
If you really want to do this by replacing the extension into a date+extension, go for a more complex case-insensitive regex -replace
like:
$ReportName -replace '^(.+)(\.[^.]+)$', "`$1_$(Get-Date -Format 'yyyy-MM-dd__HH-mm')`$2"
Regex details:
^ Assert position at the beginning of the string
( Match the regular expression below and capture its match into backreference number 1
. Match any single character that is not a line break character
+ Between one and unlimited times, as many times as possible, giving back as needed (greedy)
)
( Match the regular expression below and capture its match into backreference number 2
\. Match the character “.” literally
[^.] Match any character that is NOT a “.”
+ Between one and unlimited times, as many times as possible, giving back as needed (greedy)
)
$ Assert position at the end of the string (or before the line break at the end of the string, if any)
php add text before file extension
Try this.
$fileName = ' http://www.skizzar.com/template-fox/files/abc.jpg';
$fileArray = pathinfo($fileName);
echo $fileArray['dirname'].'/'.$fileArray['filename'].'-250x250'.'.'.$fileArray['extension'];
Here's a working demo.
Demo
Related Topics
Why Is Type Hinting Necessary in PHP
How to Create a Fluent Query Interface
How to Check in PHP That I'm in a Static Context (Or Not)
Gulp-Webapp Running Browsersync and PHP
One Form with Two Submit Buttons and Different Actions for Each Button
What's the Prefix for Binary in PHP
Fetching One Row Only with MySQLi
What Does the Percent Sign Mean in PHP
How to Check If a Value Already Exists to Avoid Duplicates
Laravel Polymorphic Relations Has Many Through
How to Connect to Database on Another Server
Is_Unique for Codeigniter Form Validation
Find Multiples of a Number in PHP
Allowing Users to Refresh Browser Without the "Confirm Form Resubmission" Pop-Up
Post Data and Retrieve the Response Using PHP Curl
Bulk Rename Files in a Folder - PHP
How to Return Custom Error Message from Controller Method Validation