PHP - insert string into filename before extension

Discussion in 'Web Design and Development' started by jordanste, Dec 8, 2008.

  1. jordanste macrumors member

    Joined:
    Feb 25, 2006
    #1
    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.
     
  2. angelwatt Moderator emeritus

    angelwatt

    Joined:
    Aug 16, 2005
    Location:
    USA
    #2
    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.
     
  3. macfaninpdx macrumors regular

    Joined:
    Mar 6, 2007
    #3
    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_partsexplode("."$filename);
    $newname $name_parts[0] . "-1" "." $name_parts[1];
     
  4. angelwatt Moderator emeritus

    angelwatt

    Joined:
    Aug 16, 2005
    Location:
    USA
    #4
    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($filename0, -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.
     
  5. macfaninpdx macrumors regular

    Joined:
    Mar 6, 2007
    #5
    ;)

    PHP:
    $pos = -strrpos($filename".");
    $filename substr($filename0$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.
     

Share This Page