Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

jordanste

macrumors member
Original poster
Feb 25, 2006
83
0
i need to insert a string into the string $filename before the file extension. i was trying to use substr_replace to do it but i dont think i understand how to use substr_replace and i cant even get it to remove the file extension.

so i need to take "file1.jpg" and change it to "file1-1.jpg"

thanks.
 
Try this out. Haven't tested though. (edit: now tested)
PHP:
$filename = preg_replace('/(.*)(\.[\w\d]{3})/', '$1-1$2', $filename);
In the above, the $1 captures the existing name of the file. $2 captures the period plus the extension of the file.
 
Also, if you know there won't be any other periods in the filename, you could explode it, modify the name, and then join it back together.
PHP:
$name_parts= explode(".", $filename);
$newname = $name_parts[0] . "-1" . "." . $name_parts[1];
 
And since there's a number of ways to skin a cat (and because I'm bored), I'll throw an additional way out.
PHP:
$filename = substr($filename, 0, -4) .'-1'. substr($filename, -4);
This assumes you're using files with a 3-letter extension. It also likely runs faster that my first solution as regexp functions take a tad longer to process (the extra time wouldn't be noticeable unless you're using a couple hundred times). This also won't have any issues if there's other . in the file besides for the extension.
 
And since there's a number of ways to skin a cat (and because I'm bored), I'll throw an additional way out.
;)

PHP:
$pos = -1 * strrpos($filename, ".");
$filename = substr($filename, 0, $pos) . '-1' . substr($filename, $pos);

I updated the above to allow for filename extensions longer than 3 characters. This method only requires that a period be used to separate the extension, but periods can also be used in the filename.
 
;)

PHP:
$pos = -1 * strrpos($filename, ".");
$filename = substr($filename, 0, $pos) . '-1' . substr($filename, $pos);

I updated the above to allow for filename extensions longer than 3 characters. This method only requires that a period be used to separate the extension, but periods can also be used in the filename.
 
Seriously... almost 9 year old thread!

It's funny, I almost posted in the Site Feedback section today, to ask if there was a way to configure a rule [in this MB] to prevent a thread that's X days old (or Y days relative) from being bumped by a new user. I see these all the time - someone stumbled on a 8+ year old thread and posts some totally irrelevant followup/response.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.