insert string into string

Discussion in 'PHP' started by bumbarov, Apr 14, 2012.

  1. #1
    Hello!

    I have images in this name format '78f666f.jpg'

    But I must replace this name with this 78f666f_thumb.jpg

    I must inject the original name '78f666f.jpg' with this piece 78f666f_thumb.jpg

    Do you have any proposal?
    Thanks!
     
    bumbarov, Apr 14, 2012 IP
  2. sarahk

    sarahk iTamer Staff

    Messages:
    28,899
    Likes Received:
    4,555
    Best Answers:
    123
    Trophy Points:
    665
    #2
    There will be a nice regex to do this but the clumsy way would be

    $filename = ''78f666f.jpg';
    $thumbfilename = str_replace('.','_thumb.',$filename);
    PHP:
    This assumes the names meet the standard of only having one full stop in the name. If there is a chance they might have more but will always be a .jpg then you could do this

    $filename = ''78f666f.jpg';
    $thumbfilename = str_replace('.jpg','_thumb.jpg',$filename);
    PHP:
     
    sarahk, Apr 14, 2012 IP
  3. ThePHPMaster

    ThePHPMaster Well-Known Member

    Messages:
    737
    Likes Received:
    52
    Best Answers:
    33
    Trophy Points:
    150
    #3
    This should work not matter what the file name is, how many periods it contains or the extension is:

    
    <?php
    // File name
    $name = 'file.a.name.234.jpg';
    
    // Find last position
    $position = strrpos($name, '.');
    
    // Replace the . with _thumb.
    echo substr_replace($name, '_thumb.', $position, 1);
    ?>
    
    PHP:
     
    ThePHPMaster, Apr 15, 2012 IP