Search code examples
phpstringsubstrstrpos

PHP add multiple strings within a string at multiple positions


While this works perfectly, looking for a way to make it a little / lot cleaner, and also to learn along the way!!! I am adding /thumbs to a directory and file string, and also adding _thumb to the end of the file name of that same string.

from this... Gallery/Test/Image/image.jpg

to this... Gallery/Test/Image/thumbs/image_thumb.jpg

but the paths can change in length depending on the directory structure, but /thumbs will always be the last directory, and _thumb will always be before the "."

    $thumb_dir = substr($file, 0, strrpos($file, '/')) . '/thumbs' . substr($file, strrpos($file, '/'));

    $thumbnail = substr($thumb_dir, 0, strrpos($thumb_dir, '.')) . '_thumb' . substr($thumb_dir, strrpos($thumb_dir, '.'));

Thanks


Solution

  • pathinfo might help you if your PHP version is > 5.2.0+

    $path_parts = pathinfo('Gallery/Test/Image/image.jpg');
    echo $path_parts['dirname'].'/thumbs/'.$path_parts['filename'].'_thumb.'.$path_parts['extension'];
    

    Little explanation of the code

    $path_parts['dirname'] would fetch the complete directory path of the path given in this case it would be Gallery/Test/Image. Then we added a directory called '/thumbs/' into the string. next we should get the name of the file using $path_parts['filename'] which would fetch image and not image.jpg and furthur we added '_thumb.' to it. and later we suffix with the extension.